﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using UYD_WCS.DBUtility;
using UYD_WCS_NX_AGV_Controller.AGV.Fork;
using UYD_WCS_NX_AGV_Controller.BaseClass;
using WebSocket4Net;


namespace UYD_WCS_NX_AGV_Controller
{
    public partial class FrmMain_XA : Form
    {
        #region 系统定义变量
        UYD_WCS.Common.INIFile iniFile = new UYD_WCS.Common.INIFile(Application.ExecutablePath + "../../SYS.ini");
        CTaskStatusValue cTaskStatus = new CTaskStatusValue();
        BackgroundWorker bgGetTask = new BackgroundWorker();
        UYD_WCS.BLL.W_TASK_AGV bllTaskAgv = new UYD_WCS.BLL.W_TASK_AGV();
        #endregion
        #region AGV定义变量

        public static WebSocket4Net.WebSocket webSocket4NetClient = null;
        AGV.AgvMsgHelper agvMsgHelper = new AGV.AgvMsgHelper();
        #endregion
        #region 串口程序控制
        private int allThreadValue = 0;
        private int InitWcsComFlag = 0;

        private Thread WcsComSendThread = null;
        private Thread WcsComRecvThread = null; 

        #region 货叉PLC线程

        private int InitSRM1ComFlag = 0;
        public static PLCOperate_AgvFork plcSRM1 = new PLCOperate_AgvFork();
        private Thread PLCSRM1ReadThread = null;
        private Thread PLCSRM1WriteThread = null;
        #endregion

        #region 系统整体控制线程

        private Thread AgvForkControlThread = null;
        #endregion

        //射频门数据定义参数
        public static int sendSPMNum = 0;
        private int sendSPMDataTimeout = 0;
        //发送后接收标志
        private byte sendSPMRecvFlag = 0x01;
        //设备连接状态
        public static int SPMLinkFlag = 0;

        private int SPMTime = 0;
        public static int SPMFirstSendFlag = 1;
        private int SPMFirstReadFlag = 0;

        private int recvSPMLen = 0;
        private byte[] recvSPMData = new byte[1000];

        #endregion

        System.Timers.Timer timerAgvHartbeatToWcs = new System.Timers.Timer();

        log4net.ILog LogWcsInfo = log4net.LogManager.GetLogger("LogWcsInfo"); //Logging 名字要在 App.config 中能找到

        public FrmMain_XA()
        {
            InitializeComponent();
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }

        private void FrmMain_XA_Load(object sender, EventArgs e)
        {
            //string strAlarmInfo = "{\"topic\": \"/diagnostics_agg\", \"msg\": {\"status\": [{\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"Too large\", \"key\": \"amcl: Standard deviation\"}, {\"value\": \"Potentially erroneous data or settings detected for a robot_localization state estimation node.\", \"key\": \"ekf_node_global: Filter diagnostic updater\"}, {\"value\": \"\", \"key\": \"ekf_node_global: odometry / filtered topic status\"}, {\"value\": \"The robot_localization state estimation node appears to be functioning properly.\", \"key\": \"ekf_node_local: Filter diagnostic updater\"}, {\"value\": \"\", \"key\": \"ekf_node_local: odometry / filtered topic status\"}], \"name\": \" / ALGORITHM / LOCALIZATION\", \"level\": 1}, {\"message\": \"Too large\", \"hardware_id\": \"None\", \"values\": [{\"value\": \"0.310645\", \"key\": \"std_x\"}, {\"value\": \"0.422146\", \"key\": \"std_y\"}, {\"value\": \"0.233443\", \"key\": \"std_yaw\"}, {\"value\": \"0.2\", \"key\": \"std_warn_level_x\"}, {\"value\": \"0.2\", \"key\": \"std_warn_level_y\"}, {\"value\": \"0.1\", \"key\": \"std_warn_level_yaw\"}], \"name\": \" / ALGORITHM / LOCALIZATION / amcl: Standard deviation\", \"level\": 1}, {\"message\": \"Potentially erroneous data or settings detected for a robot_localization state estimation node.\", \"hardware_id\": \"none\", \"values\": [{\"value\": \"3 absolute pose inputs detected for X.This may result in oscillations.Please ensure that your variances for each measured variable are set appropriately.\", \"key\": \"X_configuration\"}, {\"value\": \"3 absolute pose inputs detected for YAW.This may result in oscillations.Please ensure that your variances for each measured variable are set appropriately.\", \"key\": \"YAW_configuration\"}, {\"value\": \"3 absolute pose inputs detected for Y.This may result in oscillations.Please ensure that your variances for each measured variable are set appropriately.\", \"key\": \"Y_configuration\"}], \"name\": \" / ALGORITHM / LOCALIZATION / ekf_node_global: Filter diagnostic updater\", \"level\": 1}, {\"message\": \"\", \"hardware_id\": \"none\", \"values\": [{\"value\": \"206\", \"key\": \"Events in window\"}, {\"value\": \"8730\", \"key\": \"Events since startup\"}, {\"value\": \"10.300034\", \"key\": \"Duration of window(s)\"}, {\"value\": \"19.999934\", \"key\": \"Actual frequency(Hz)\"}, {\"value\": \"16.200000\", \"key\": \"Minimum acceptable frequency(Hz)\"}, {\"value\": \"24.200000\", \"key\": \"Maximum acceptable frequency(Hz)\"}], \"name\": \" / ALGORITHM / LOCALIZATION / ekf_node_global: odometry filtered topic status\", \"level\": 0}, {\"message\": \"The robot_localization state estimation node appears to be functioning properly.\", \"hardware_id\": \"none\", \"values\": [], \"name\": \" / ALGORITHM / LOCALIZATION / ekf_node_local: Filter diagnostic updater\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"none\", \"values\": [{\"value\": \"506\", \"key\": \"Events in window\"}, {\"value\": \"21821\", \"key\": \"Events since startup\"}, {\"value\": \"10.119866\", \"key\": \"Duration of window(s)\"}, {\"value\": \"50.000663\", \"key\": \"Actual frequency(Hz)\"}, {\"value\": \"43.200000\", \"key\": \"Minimum acceptable frequency(Hz)\"}, {\"value\": \"57.200000\", \"key\": \"Maximum acceptable frequency(Hz)\"}], \"name\": \" / ALGORITHM / LOCALIZATION / ekf_node_local: odometry filtered topic status\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"obstacle free\", \"key\": \"cmd_vel_filter: obstacle status\"}], \"name\": \" / ALGORITHM / OBSTACLE\", \"level\": 0}, {\"message\": \"obstacle free\", \"hardware_id\": \"obstacle\", \"values\": [], \"name\": \" / ALGORITHM / OBSTACLE / cmd_vel_filter: obstacle status\", \"level\": 0}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"Warning\", \"key\": \"LOCALIZATION\"}, {\"value\": \"OK\", \"key\": \"OBSTACLE\"}], \"name\": \" / ALGORITHM\", \"level\": 1}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"rosbridge_battery: Battery topic status\"}, {\"value\": \"\", \"key\": \"rosbridge_battery: Hardware status\"}], \"name\": \" / DEVICES / BATTERY\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_battery\", \"values\": [{\"value\": \"8\", \"key\": \"Events in window\"}, {\"value\": \"435\", \"key\": \"Events since startup\"}, {\"value\": \"7.999969\", \"key\": \"Duration of window(s)\"}, {\"value\": \"1.000004\", \"key\": \"Actual frequency(Hz)\"}, {\"value\": \"0.450000\", \"key\": \"Minimum acceptable frequency(Hz)\"}, {\"value\": \"1.100000\", \"key\": \"Maximum acceptable frequency(Hz)\"}], \"name\": \" / DEVICES / BATTERY / rosbridge_battery: Battery topic status\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_battery\", \"values\": [{\"value\": \" / dev / usb_right4\", \"key\": \"serial_port\"}, {\"value\": \"beyonder\", \"key\": \"vendor_name\"}], \"name\": \" / DEVICES / BATTERY / rosbridge_battery: Hardware status\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"rosbridge_drive: Hardware status\"}, {\"value\": \"\", \"key\": \"rosbridge_drive: Odom topic status\"}], \"name\": \" / DEVICES / DRIVE\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_footprint\", \"values\": [{\"value\": \" / dev / usb_right2\", \"key\": \"serial_port\"}, {\"value\": \"akelc\", \"key\": \"vendor_name\"}, {\"value\": \"3\", \"key\": \"estop\"}], \"name\": \" / DEVICES / DRIVE / rosbridge_drive: Hardware status\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_footprint\", \"values\": [{\"value\": \"253\", \"key\": \"Events in window\"}, {\"value\": \"21813\", \"key\": \"Events since startup\"}, {\"value\": \"5.059972\", \"key\": \"Duration of window(s)\"}, {\"value\": \"50.000272\", \"key\": \"Actual frequency(Hz)\"}, {\"value\": \"22.500000\", \"key\": \"Minimum acceptable frequency(Hz)\"}, {\"value\": \"55.000000\", \"key\": \"Maximum acceptable frequency(Hz)\"}], \"name\": \" / DEVICES / DRIVE / rosbridge_drive: Odom topic status\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"rosbridge_imu: Hardware status\"}, {\"value\": \"\", \"key\": \"rosbridge_imu: Imu topic status\"}], \"name\": \" / DEVICES / IMU\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_imu\", \"values\": [{\"value\": \" / dev / usb_right3\", \"key\": \"serial_port\"}, {\"value\": \"wit\", \"key\": \"vendor_name\"}, {\"value\": \"0\", \"key\": \"imu / temperature\"}], \"name\": \" / DEVICES / IMU / rosbridge_imu: Hardware status\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_imu\", \"values\": [{\"value\": \"254\", \"key\": \"Events in window\"}, {\"value\": \"21832\", \"key\": \"Events since startup\"}, {\"value\": \"5.080035\", \"key\": \"Duration of window(s)\"}, {\"value\": \"49.999657\", \"key\": \"Actual frequency(Hz)\"}, {\"value\": \"22.500000\", \"key\": \"Minimum acceptable frequency(Hz)\"}, {\"value\": \"55.000000\", \"key\": \"Maximum acceptable frequency(Hz)\"}], \"name\": \" / DEVICES / IMU / rosbridge_imu: Imu topic status\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"scan_rectifier: scan_laser topic status\"}], \"name\": \" / DEVICES / LASER\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [{\"value\": \"80\", \"key\": \"Events in window\"}, {\"value\": \"6593\", \"key\": \"Events since startup\"}, {\"value\": \"5.312792\", \"key\": \"Duration of window(s)\"}, {\"value\": \"15.057996\", \"key\": \"Actual frequency(Hz)\"}, {\"value\": \"9.000000\", \"key\": \"Minimum acceptable frequency(Hz)\"}, {\"value\": \"55.000000\", \"key\": \"Maximum acceptable frequency(Hz)\"}], \"name\": \" / DEVICES / LASER / scan_rectifier: scan_laser topic status\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"rosbridge_plc: Hardware status\"}, {\"value\": \"\", \"key\": \"rosbridge_plc: Plc topic status\"}], \"name\": \" / DEVICES / PLC\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_plc\", \"values\": [{\"value\": \"192.168.0.14\", \"key\": \"serial_port\"}, {\"value\": \"modbus\", \"key\": \"vendor_name\"}, {\"value\": \"1\", \"key\": \"estop\"}], \"name\": \" / DEVICES / PLC / rosbridge_plc: Hardware status\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"base_plc\", \"values\": [{\"value\": \"255\", \"key\": \"Events in window\"}, {\"value\": \"21873\", \"key\": \"Events since startup\"}, {\"value\": \"5.100020\", \"key\": \"Duration of window(s)\"}, {\"value\": \"49.999805\", \"key\": \"Actual frequency(Hz)\"}, {\"value\": \"22.500000\", \"key\": \"Minimum acceptable frequency(Hz)\"}, {\"value\": \"55.000000\", \"key\": \"Maximum acceptable frequency(Hz)\"}], \"name\": \" / DEVICES / PLC / rosbridge_plc: Plc topic status\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"OK\", \"key\": \"BATTERY\"}, {\"value\": \"OK\", \"key\": \"DRIVE\"}, {\"value\": \"OK\", \"key\": \"IMU\"}, {\"value\": \"OK\", \"key\": \"LASER\"}, {\"value\": \"OK\", \"key\": \"PLC\"}], \"name\": \" / DEVICES\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"action / dump\"}], \"name\": \" / STATUS / ACTION / DUMP\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / ACTION / DUMP / action dump\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"action / load\"}], \"name\": \" / STATUS / ACTION / LOAD\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / ACTION / LOAD / action load\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"OK\", \"key\": \"DUMP\"}, {\"value\": \"OK\", \"key\": \"LOAD\"}], \"name\": \" / STATUS / ACTION\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"todo\", \"key\": \"estop / area\"}], \"name\": \" / STATUS / ESTOP / AREA\", \"level\": 0}, {\"message\": \"todo\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / ESTOP / AREA / estop area\", \"level\": 0}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"estop / base\"}], \"name\": \" / STATUS / ESTOP / BASE\", \"level\": 1}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [{\"value\": \"3\", \"key\": \"estop_status\"}], \"name\": \" / STATUS / ESTOP / BASE / estop base\", \"level\": 1}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"estop / safe\"}], \"name\": \" / STATUS / ESTOP / SAFE\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / ESTOP / SAFE / estop safe\", \"level\": 0}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"terminal\", \"key\": \"estop / terminal\"}], \"name\": \" / STATUS / ESTOP / TERMINAL\", \"level\": 1}, {\"message\": \"terminal\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / ESTOP / TERMINAL / estop terminal\", \"level\": 1}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"OK\", \"key\": \"AREA\"}, {\"value\": \"Warning\", \"key\": \"BASE\"}, {\"value\": \"OK\", \"key\": \"SAFE\"}, {\"value\": \"Warning\", \"key\": \"TERMINAL\"}], \"name\": \" / STATUS / ESTOP\", \"level\": 1}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / MAINTENANCE\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"motion / back\"}], \"name\": \" / STATUS / MOTION / BACK\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / MOTION / BACK / motion back\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"motion / left\"}], \"name\": \" / STATUS / MOTION / LEFT\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / MOTION / LEFT / motion left\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"motion / right\"}], \"name\": \" / STATUS / MOTION / RIGHT\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / MOTION / RIGHT / motion right\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"OK\", \"key\": \"BACK\"}, {\"value\": \"OK\", \"key\": \"LEFT\"}, {\"value\": \"OK\", \"key\": \"RIGHT\"}], \"name\": \" / STATUS / MOTION\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"start / buzzer\"}], \"name\": \" / STATUS / START / BUZZER\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / START / BUZZER / start buzzer\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"start / enable\"}], \"name\": \" / STATUS / START / ENABLE\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / START / ENABLE / start enable\", \"level\": 0}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"start / modex\"}], \"name\": \" / STATUS / START / MODEX\", \"level\": 1}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / START / MODEX / start modex\", \"level\": 1}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"start / pedal\"}], \"name\": \" / STATUS / START / PEDAL\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / START / PEDAL / start pedal\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"start / power\"}], \"name\": \" / STATUS / START / POWER\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / START / POWER / start power\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"start / relay\"}], \"name\": \" / STATUS / START / RELAY\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / START / RELAY / start relay\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"start / stick\"}], \"name\": \" / STATUS / START / STICK\", \"level\": 0}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / START / STICK / start stick\", \"level\": 0}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"OK\", \"key\": \"BUZZER\"}, {\"value\": \"OK\", \"key\": \"ENABLE\"}, {\"value\": \"Warning\", \"key\": \"MODEX\"}, {\"value\": \"OK\", \"key\": \"PEDAL\"}, {\"value\": \"OK\", \"key\": \"POWER\"}, {\"value\": \"OK\", \"key\": \"RELAY\"}, {\"value\": \"OK\", \"key\": \"STICK\"}], \"name\": \" / STATUS / START\", \"level\": 1}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"auto_task\", \"key\": \"task / behavior\"}], \"name\": \" / STATUS / TASK / BEHAVIOR\", \"level\": 1}, {\"message\": \"auto_task\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / TASK / BEHAVIOR / task behavior\", \"level\": 1}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"going_L0101 - auto_task\", \"key\": \"task / state\"}], \"name\": \" / STATUS / TASK / STATE\", \"level\": 1}, {\"message\": \"going_L0101 - auto_task\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / STATUS / TASK / STATE / task state\", \"level\": 1}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"Warning\", \"key\": \"BEHAVIOR\"}, {\"value\": \"Warning\", \"key\": \"STATE\"}], \"name\": \" / STATUS / TASK\", \"level\": 1}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"OK\", \"key\": \"ACTION\"}, {\"value\": \"Warning\", \"key\": \"ESTOP\"}, {\"value\": \"OK\", \"key\": \"MAINTENANCE\"}, {\"value\": \"OK\", \"key\": \"MOTION\"}, {\"value\": \"Warning\", \"key\": \"START\"}, {\"value\": \"Warning\", \"key\": \"TASK\"}], \"name\": \" / STATUS\", \"level\": 1}, {\"message\": \"OK\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / SYSTEM\", \"level\": 0}, {\"message\": \"Warning\", \"hardware_id\": \"\", \"values\": [{\"value\": \"\", \"key\": \"estop / light\"}, {\"value\": \"\", \"key\": \"hahaestop / hahaarea\"}, {\"value\": \"OK\", \"key\": \"jsnode: Joystick Driver Status\"}], \"name\": \" / Other\", \"level\": 1}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / Other / estop light\", \"level\": 1}, {\"message\": \"\", \"hardware_id\": \"\", \"values\": [], \"name\": \" / Other / hahaestop hahaarea\", \"level\": 0}, {\"message\": \"OK\", \"hardware_id\": \"none\", \"values\": [{\"value\": \" / joy\", \"key\": \"topic\"}, {\"value\": \" / dev / input / js0\", \"key\": \"device\"}, {\"value\": \"\", \"key\": \"device name\"}, {\"value\": \"0.1\", \"key\": \"dead zone\"}, {\"value\": \"10\", \"key\": \"autorepeat rate(Hz)\"}, {\"value\": \"0.1\", \"key\": \"coalesce interval(s)\"}, {\"value\": \"0\", \"key\": \"recent joystick event rate (Hz)\"}, {\"value\": \"9.98596\", \"key\": \"recent publication rate(Hz)\"}, {\"value\": \"1\", \"key\": \"subscribers\"}, {\"value\": \"False\", \"key\": \"default trig val\"}, {\"value\": \"False\", \"key\": \"sticky buttons\"}], \"name\": \"/Other/jsnode: Joystick Driver Status\", \"level\": 0}], \"header\": {\"stamp\": {\"secs\": 1695123452, \"nsecs\": 200440413}, \"frame_id\": \"\", \"seq\": 437}}, \"op\": \"publish\"}";

            //AGV.Model.AlarmReport alarmReport = new AGV.Model.AlarmReport();
            //alarmReport = Newtonsoft.Json.JsonConvert.DeserializeObject<AGV.Model.AlarmReport>(strAlarmInfo);
            //foreach(AGV.Model.AlarmStatusItem aStatus in alarmReport.msg.status)
            //{
            //    if (aStatus.name.Replace(" ","") == "/STATUS/ESTOP")
            //    {
            //        if(aStatus.level==1)
            //        {
            //            string str = "AGV急停被触发";
            //        }
            //    }
            //}

            UYD_WCS.Model.W_TASK_AGV modelTaskAgv = new UYD_WCS.Model.W_TASK_AGV();
            modelTaskAgv.TASK_ID = 12345;
            modelTaskAgv.TASK_NO = DateTime.Now.ToString("yyyyMMddHHmmss");
            modelTaskAgv.TASK_FLAG = "02";
            modelTaskAgv.GET_LOC = "01010101";
            modelTaskAgv.SET_LOC = "01020301";
            modelTaskAgv.TASK_DATE = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            modelTaskAgv.TASK_STATUS_CODE = 0;

            string strJson = Newtonsoft.Json.JsonConvert.SerializeObject(modelTaskAgv);

            byte[]btemp= Encoding.Default.GetBytes(strJson);

            InitGlobalVariable();

            #region 初始化wcs连接串口
            InitCom();
            #endregion
            #region 连接Agv端口

            ConnectWebsocket();
            #endregion

            #region 后台获取可执行的任务单号
            //InitializeBackgroundWorker();
            //bgGetTask.RunWorkerAsync();
            #endregion

            #region AGV，货叉状态上报给WCS
            timerAgvHartbeatToWcs.Interval = 6000;
            timerAgvHartbeatToWcs.Elapsed += TimerAgvtimerAgvHartbeatToWcsToWcs_Elapsed;
            timerAgvHartbeatToWcs.Enabled = true;
            timerAgvHartbeatToWcs.Start();
            #endregion

            cTaskStatus.AgvReportTaskStatusChangeEvent += CTaskStatus_AgvReportTaskStatusChangeEvent;
            //cTaskStatus.ReceiveNewTaskEvent += CTaskStatus_ReceiveNewTaskEvent;
            cTaskStatus.ReceiveTaskCancleEvent += CTaskStatus_ReceiveTaskCancleEvent;

            cTaskStatus.AgvAutoChangeEvent += CTaskStatus_AgvAutoChangeEvent;

            cTaskStatus.SRM_GetGoodsApplyEnent += CTaskStatus_SRM_GetGoodsApplyEnent;
            cTaskStatus.SRM_SetGoodsApplyEnent += CTaskStatus_SRM_SetGoodsApplyEnent;

            #region 货叉
            cTaskStatus.SRM_Get_Finish_Event += CTaskStatus_SRM_Get_Finish_Event;
            cTaskStatus.SRM_Set_Finish_Event += CTaskStatus_SRM_Set_Finish_Event;
            cTaskStatus.SRM_Task_Finish_Event += CTaskStatus_SRM_Task_Finish_Event;
            #endregion

            InitComThread();

        }

        private void CTaskStatus_AgvAutoChangeEvent(object sender, EventArgs e)
        {
            try
            {
                if (tbToLoc.Text == "") return;
                if (tbToLoc.Text.Length < 5) return;
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                List<string> listInputValue = new List<string>();
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("tochargepoint_task", listInputKey, listInputValue));


                AddListBak("AGV自动充电任务下发完成");
            }
            catch (Exception exc)
            {

            }
        }

        private void CTaskStatus_SRM_Task_Finish_Event(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
        }

        private void CTaskStatus_SRM_Set_Finish_Event(object sender, EventArgs e)
        {
            try
            {
                if (CTaskInfo.CurrentTask != null)
                {
                    if (CTaskInfo.CurrentTask.TASK_FLAG == "02")
                    {
                        if (cTaskStatus.SRM_Alarm == 0 && cTaskStatus.SRM_ForkIsHasGood == 0 && cTaskStatus.Task_Status == 6)
                        {
                            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
                            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 7);
                        }
                    }
                    else if (CTaskInfo.CurrentTask.TASK_FLAG == "01")
                    {
                        if (cTaskStatus.SRM_Alarm == 0 && cTaskStatus.SRM_ForkIsHasGood == 0 && cTaskStatus.Task_Status == 6)
                        {
                            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
                            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 7);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                AddListBak("取货完成后,数据处理异常" + exc.Message + exc.StackTrace);
            }
        }

        private void CTaskStatus_SRM_Get_Finish_Event(object sender, EventArgs e)
        {
            try
            {
                if (CTaskInfo.CurrentTask != null)
                {
                    if (CTaskInfo.CurrentTask.TASK_FLAG == "02")
                    {
                        if (cTaskStatus.SRM_Alarm == 0 && cTaskStatus.SRM_ForkIsHasGood == 1 && cTaskStatus.Task_Status == 3)
                        {
                            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
                            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 4);
                        }
                    }
                    else if (CTaskInfo.CurrentTask.TASK_FLAG == "01")
                    {
                        if (cTaskStatus.SRM_Alarm == 0 && cTaskStatus.SRM_ForkIsHasGood == 1 && cTaskStatus.Task_Status == 3)
                        {
                            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
                            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 4);
                        }
                    }
                }
            }
            catch(Exception exc)
            {
                AddListBak("取货完成后,数据处理异常" + exc.Message+exc.StackTrace);
            }
        }

        private void CTaskStatus_SRM_GetGoodsApplyEnent(object sender, EventArgs e)
        {
            try
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_GetGoodsAllow_ToPlc_Addr, 1, 1, 1, 1);
                AddListBak(" 给货叉PLC DB540.44.0 下发取货允许=1指令");
            }
            catch (Exception exc)
            {
                AddListBak("给输送线下发取货允许时异常");
            }

        }
        private void CTaskStatus_SRM_SetGoodsApplyEnent(object sender, EventArgs e)
        {
            try
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_SetGoodsAllow_ToPlc_Addr, 1, 1, 1, 1);
                AddListBak(" 给货叉PLC DB540.46.0 下发放货允许=1指令");
            }
            catch (Exception exc)
            {
                AddListBak("给输送线下发放货允许时异常");
            }
        }


        private void TimerAgvtimerAgvHartbeatToWcsToWcs_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                lbWcsLinkStatus.Invoke(new EventHandler(delegate {
                    lbWcsLinkStatus.BackColor = Color.LightSteelBlue;
                }));

                CTaskInfo.AddToWcsSendDataList(0x02, 0x00, 0x01);

                if (CTaskInfo.CurrentTask == null && cTaskStatus.AgvAutoChange==0)
                    CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x00);
            }
            catch(Exception exc)
            {

                AddListBak("AGV状态上报时异常");
            }
        }

        private string GetAGVLocNo(string locno)
        {
            return "L" + locno.Substring(0, 4);
        }
        /// <summary>
        /// 取货前货叉移动之前检查货叉状态
        /// </summary>
        /// <returns></returns>
        private bool CheckForkStatus_Before_Move_Get()
        {
            if(cTaskStatus.SRM_RemoteAuto==0)
            {
                AddListBak("取货前的货叉移动时,当前货叉远程自动模式未启动!");
                return false;
            }
            else if (cTaskStatus.SRM_Alarm == 1)
            {
                AddListBak("取货前的货叉移动时,当前货叉报警未消除!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkInZero == 0)
            {
                AddListBak("取货前的货叉移动时,当前货叉未在原点!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkIsHasGood == 1)
            {
                AddListBak("取货前的货叉移动时,当前货叉有货!");
                return false;
            }
            else if (cTaskStatus.SRM_Status == 1)
            {
                AddListBak("取货前的货叉移动时,当前货叉非空闲状态!");
                return false;
            }
            else 
            {
                return true;
            }
        }

        /// <summary>
        /// 放货前货叉移动之前检查货叉状态
        /// </summary>
        /// <returns></returns>
        private bool CheckForkStatus_Before_Move_Set()
        {
            if (cTaskStatus.SRM_RemoteAuto == 0)
            {
                AddListBak("放货前的货叉移动时,当前货叉远程自动模式未启动!");
                return false;
            }
            else if (cTaskStatus.SRM_Alarm == 1)
            {
                AddListBak("放货前的货叉移动时,当前货叉报警未消除!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkInZero == 0)
            {
                AddListBak("放货前的货叉移动时,当前货叉未在原点!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkIsHasGood == 0)
            {
                AddListBak("放货前的货叉移动时,当前货叉无货!");
                return false;
            }
            else if (cTaskStatus.SRM_Status == 1)
            {
                AddListBak("放货前的货叉移动时,当前货叉非空闲状态!");
                return false;
            }
            else if (cTaskStatus.SRM_Task_Finish == 1)
            {
                AddListBak("放货前的货叉移动时,当前货叉已移动完成!");
                return false;
            }
            else if (CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc)
            {
                AddListBak("放货前的货叉移动时,当前货叉放货移动指令已发送!");
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 货叉取货前检查货叉状态
        /// </summary>
        /// <returns></returns>
        private bool CheckForkStatus_Before_Get()
        {
            if (cTaskStatus.SRM_RemoteAuto == 0)
            {
                AddListBak("取货时,当前货叉远程自动模式未启动!");
                return false;
            }
            else if (cTaskStatus.SRM_Alarm == 1)
            {
                AddListBak("取货时,当前货叉报警未消除!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkInZero == 0)
            {
                AddListBak("取货时,当前货叉未在原点!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkIsHasGood == 1)
            {
                AddListBak("取货时,当前货叉有货!");
                return false;
            }
            else if (cTaskStatus.SRM_Status == 1)
            {
                AddListBak("取货时,当前货叉非空闲状态!");
                return false;
            }
            else if (cTaskStatus.SRM_Task_Finish == 0)
            {
                AddListBak("取货时,当前货叉取货时未移动到位!");
                return false;
            }
            else if (CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc)
            {
                AddListBak("取货时,当前货叉取货指令已发送!");
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 货叉放货前检查货叉状态
        /// </summary>
        /// <returns></returns>
        private bool CheckForkStatus_Before_Set()
        {
            if (cTaskStatus.SRM_RemoteAuto == 0)
            {
                AddListBak("放货时,当前货叉远程自动模式未启动!");
                return false;
            }
            else if (cTaskStatus.SRM_Alarm == 1)
            {
                AddListBak("放货时,当前货叉报警未消除!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkInZero == 0)
            {
                AddListBak("放货时,当前货叉未在原点!");
                return false;
            }
            else if (cTaskStatus.SRM_ForkIsHasGood == 0)
            {
                AddListBak("放货时,当前货叉无货!");
                return false;
            }
            else if (cTaskStatus.SRM_Status == 1)
            {
                AddListBak("放货时,当前货叉非空闲状态!");
                return false;
            }
            else if (cTaskStatus.SRM_Task_Finish == 0)
            {
                AddListBak("放货时,当前货叉放货时未移动到位!");
                return false;
            }
            else if (CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc)
            {
                AddListBak("放货时,当前货叉放货指令已发送!");
                return false;
            }
            else
            {
                return true;
            }
        }

        private void CTaskStatus_ReceiveTaskCancleEvent(object sender, EventArgs e)
        {
            try
            {
                UYD_WCS.Model.W_TASK_AGV modelTaskAgv = Newtonsoft.Json.JsonConvert.DeserializeObject<UYD_WCS.Model.W_TASK_AGV>(cTaskStatus.ReceiveTaskCancle);
                string strWhere = " TASK_NO='" + modelTaskAgv.TASK_NO + "' AND GET_LOC='" + modelTaskAgv.GET_LOC + "' AND SET_LOC='" + modelTaskAgv.SET_LOC + "' ";
                if (!bllTaskAgv.Exists(strWhere))
                {
                    UpdateTaskStatus(modelTaskAgv.TASK_ID, 9);
                    AddListBak("接收到任务取消指令,取消成功!任务编号=" + modelTaskAgv.TASK_NO);
                    if (CTaskInfo.CurrentTask != null)
                    {
                        if (CTaskInfo.CurrentTask.TASK_NO == modelTaskAgv.TASK_NO)
                        {
                            webSocket4NetClient.Send(agvMsgHelper.GetTaskCancleCode());

                            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);//货叉任务先清0
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                AddListBak("处理接收任务数据错误," + exc.Message + exc.StackTrace);
            }
        }

        //private void CTaskStatus_ReceiveNewTaskEvent(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        //AddListBak("接收到新任务，" + cTaskStatus.ReceiveNewTask);
        //        //UYD_WCS.Model.W_TASK_AGV modelTaskAgv = Newtonsoft.Json.JsonConvert.DeserializeObject<UYD_WCS.Model.W_TASK_AGV>(cTaskStatus.ReceiveNewTask);
        //        //string strWhere = " TASK_NO='"+modelTaskAgv.TASK_NO+"' AND GET_LOC='"+modelTaskAgv.GET_LOC+"' AND SET_LOC='"+modelTaskAgv.SET_LOC+"' ";
        //        //if (!bllTaskAgv.Exists(strWhere))
        //        //{
        //        //    modelTaskAgv.TASK_ID=bllTaskAgv.GetMaxID();
        //        //    modelTaskAgv.TASK_STATUS_CODE = 1;
        //        //    bllTaskAgv.Add(modelTaskAgv);
        //        //    AddListBak("接收到新任务,存储成功!"+cTaskStatus.ReceiveNewTask);
        //        //}
        //    }
        //    catch(Exception exc)
        //    {
        //        AddListBak("处理接收任务数据错误," + exc.Message + exc.StackTrace);
        //    }
        //}


        public void InitComThread()
        {
            try
            {
                if (InitWcsComFlag > 0)
                {
                    //发送数据处理线程
                    WcsComSendThread = new Thread(new ThreadStart(UnitSPSendData));
                    WcsComSendThread.IsBackground = true;
                    WcsComSendThread.Start();
                    //接收数据处理线程
                    WcsComRecvThread = new Thread(new ThreadStart(UnitSPRecvData));
                    WcsComRecvThread.IsBackground = true;
                    WcsComRecvThread.Start();

                }
                if (InitSRM1ComFlag > 0)
                {
                    PLCSRM1ReadThread = new Thread(new ThreadStart(UnitPLCSRM_Read));
                    PLCSRM1ReadThread.Start();
                    PLCSRM1WriteThread = new Thread(new ThreadStart(UnitPLCSRM_Write));
                    PLCSRM1WriteThread.Start();
                }

                AgvForkControlThread = new Thread(new ThreadStart(AgvForkControlStart));
                AgvForkControlThread.Start();

            }
            catch (Exception s)
            {
                AddListBak("初始化串口线程异常" + s.Message);
            }
        }

        #region 系统整体控制线程

        /// <summary>
        /// 货叉状态读取线程
        /// </summary>
        private void AgvForkControlStart()
        {
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;

                try
                {
                    //---------------------------------start----------------------------------//
                    string strWhere = " TASK_STATUS_CODE<9 ";
                    CTaskInfo.CurrentTask = bllTaskAgv.GetModel(strWhere);
                    if (CTaskInfo.CurrentTask != null)
                    {
                        if (!string.IsNullOrEmpty(CTaskInfo.CurrentTask.TASK_NO))
                        {
                            CTaskInfo.IsHasTask = true;
                            lbTaskFlag.Invoke(new EventHandler(delegate {
                                if (CTaskInfo.CurrentTask.TASK_FLAG == "02")
                                    lbTaskFlag.Text = "入库";
                                else if (CTaskInfo.CurrentTask.TASK_FLAG == "01")
                                    lbTaskFlag.Text = "出库";
                                else if (CTaskInfo.CurrentTask.TASK_FLAG == "03")
                                    lbTaskFlag.Text = "盘库";
                            }));
                            lbTaskNo.Invoke(new EventHandler(delegate {
                                lbTaskNo.Text = CTaskInfo.CurrentTask.TASK_NO;
                            }));
                            lbTaskDateTime.Invoke(new EventHandler(delegate {
                                lbTaskDateTime.Text = CTaskInfo.CurrentTask.TASK_DATE;
                            }));
                            lbTaskGetLoc.Invoke(new EventHandler(delegate {
                                lbTaskGetLoc.Text = CTaskInfo.CurrentTask.GET_LOC;
                            }));
                            lbTaskSetLoc.Invoke(new EventHandler(delegate {
                                lbTaskSetLoc.Text = CTaskInfo.CurrentTask.SET_LOC;
                            }));

                            CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
                            cTaskStatus.Task_Status = (int)CTaskInfo.CurrentTask.TASK_STATUS_CODE;
                            if (CTaskInfo.CurrentTask.TASK_FLAG == "02")
                            {
                                if (cTaskStatus.Task_Status == 1)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "待执行";
                                        lbTaskStatus.BackColor = Color.Yellow;
                                    }));

                                    if (CTaskInfo.AgvCurrentLoc != CTaskInfo.AgvGetSetPointLoc)
                                    {
                                        AddListBak("AGV未到达取放货口");
                                        Thread.Sleep(1000);
                                        continue;
                                    }

                                    if (CheckForkStatus_Before_Move_Get())
                                    {
                                        if (cTaskStatus.SRM_Task_Finish == 1)
                                        {
                                            AddListBak("当前货叉已移动完成!");

                                            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 2);
                                        }
                                        else
                                        {
                                            if (CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc)
                                            {
                                                AddListBak("当前货叉取货移动指令已发送!");
                                                Thread.Sleep(1000);
                                                continue;
                                            }
                                            else
                                            {
                                                short shRow = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2));
                                                short shCell = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(2, 2));
                                                short shFloor = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(4, 2));
                                                AGVForkSendCode(shRow, shCell, shFloor, 1);
                                                AddListBak("取货前货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.GET_LOC);

                                                CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = true;

                                                CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                                UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 2);
                                            }
                                        }
                                    }

                                }
                                else if (cTaskStatus.Task_Status == 2)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "取货行走中";
                                    }));

                                    if (CTaskInfo.AgvCurrentLoc != CTaskInfo.AgvGetSetPointLoc)
                                    {
                                        AddListBak("AGV未到达取放货口");
                                        Thread.Sleep(1000);
                                        continue;
                                    }
                                    else
                                    {
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                        UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 3);
                                    }
                                }
                                else if (cTaskStatus.Task_Status == 3)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "到达取货位";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));
                                    if (CheckForkStatus_Before_Get())
                                    {
                                        short shRow = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2));
                                        short shCell = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(2, 2));
                                        short shFloor = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(4, 2));
                                        AGVForkSendCode(shRow, shCell, shFloor, 2);
                                        AddListBak("取货任务下发完成,取货货位:" + CTaskInfo.CurrentTask.GET_LOC);

                                        CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                    }
                                }
                                else if (cTaskStatus.Task_Status == 4)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "取货完成";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    if (!CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv)
                                    {
                                        if (CTaskInfo.WareName == "XA")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L0000R");
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
                                        }
                                        else if (CTaskInfo.WareName == "XJ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L0000R");
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
                                        }
                                        else if (CTaskInfo.WareName == "HY")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L0000R");
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务

                                        }
                                        else if (CTaskInfo.WareName == "ZN")
                                        {

                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务

                                        }
                                        else if (CTaskInfo.WareName == "HGZ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务

                                        }
                                        AddListBak("取货完成,给AGV下发放货行走任务");
                                        CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                    }

                                }
                                else if (cTaskStatus.Task_Status == 5)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "放货行走中";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));
                                }
                                else if (cTaskStatus.Task_Status == 6)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "到达放货位";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    if (CheckForkStatus_Before_Move_Set())
                                    {
                                        short shRow = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2));
                                        short shCell = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(2, 2));
                                        short shFloor = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(4, 2));
                                        AGVForkSendCode(shRow, shCell, shFloor, 1);
                                        AddListBak("放货前货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.SET_LOC);

                                        CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                    }

                                    if (CheckForkStatus_Before_Set())
                                    {
                                        short shRow = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2));
                                        short shCell = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(2, 2));
                                        short shFloor = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(4, 2));
                                        AGVForkSendCode(shRow, shCell, shFloor, 3);
                                        AddListBak("放货任务下发完成,放货货位:" + CTaskInfo.CurrentTask.SET_LOC);

                                        CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                    }
                                }
                                else if (cTaskStatus.Task_Status == 7)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "放货完成";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    if (!CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv)
                                    {

                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));

                                        if (CTaskInfo.WareName == "XA")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add("L0000C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }
                                        else if (CTaskInfo.WareName == "XJ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add("L0000C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }
                                        else if (CTaskInfo.WareName == "HY")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add("L0000C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }
                                        else if (CTaskInfo.WareName == "ZN")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }
                                        else if (CTaskInfo.WareName == "HGZ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }

                                        AddListBak("放货完成,给AGV下发返回取放口任务");
                                        CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv = true;
                                    }

                                }
                                else if (cTaskStatus.Task_Status == 8)
                                {
                                    #region 任务完成
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "任务完成";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));


                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 9);
                                    AddListBak("AGV返回到取放口，任务完成");

                                    CTaskInfo.IsHasTask = false;
                                    FlushPage();
                                    CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = false;
                                    CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = false;
                                    CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = false;
                                    CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = false;

                                    CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = false;
                                    CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv = false;


                                    AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
                                    #endregion
                                }
                            }
                            else if (CTaskInfo.CurrentTask.TASK_FLAG == "01")
                            {
                                if (cTaskStatus.Task_Status == 1)
                                {

                                    if (CTaskInfo.AgvCurrentLoc != CTaskInfo.AgvGetSetPointLoc)
                                    {
                                        AddListBak("AGV未到达取放货口");
                                        Thread.Sleep(50);
                                        continue;
                                    }

                                    if (!CTaskInfo.Check_MoveToGetLoc_SendedToAgv)
                                    {
                                        if (CTaskInfo.WareName == "XA")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L0000R");
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
                                        }
                                        else if (CTaskInfo.WareName == "XJ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L0000R");
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
                                        }
                                        else if (CTaskInfo.WareName == "HY")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L0000R");
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
                                        }
                                        else if (CTaskInfo.WareName == "ZN")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务


                                        }
                                        else if (CTaskInfo.WareName == "HGZ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00R");
                                            listInputValue.Add(GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC));
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务

                                        }
                                        AddListBak("给AGV下发到" + CTaskInfo.CurrentTask.GET_LOC + "行走任务");
                                        CTaskInfo.Check_MoveToGetLoc_SendedToAgv = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));


                                        lbTaskStatus.Invoke(new EventHandler(delegate
                                        {
                                            lbTaskStatus.Text = "取货行走中";
                                            lbTaskStatus.BackColor = Color.Lime;
                                        }));
                                    }

                                    if (CheckForkStatus_Before_Move_Get())
                                    {
                                        if (cTaskStatus.SRM_Task_Finish == 1)
                                        {
                                            AddListBak("当前货叉已移动完成!");

                                            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 2);
                                        }
                                        else
                                        {
                                            if (CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc)
                                            {
                                                AddListBak("当前货叉取货移动指令已发送!");
                                                Thread.Sleep(1000);
                                                continue;
                                            }
                                            else
                                            {
                                                short shRow = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2));
                                                short shCell = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(2, 2));
                                                short shFloor = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(4, 2));
                                                AGVForkSendCode(shRow, shCell, shFloor, 1);
                                                AddListBak("取货前货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.GET_LOC);

                                                CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = true;
                                            }
                                        }
                                    }
                                }
                                else if (cTaskStatus.Task_Status == 2)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "取货行走中";
                                    }));
                                    CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                }
                                else if (cTaskStatus.Task_Status == 3)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "到达取货位";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));
                                    if (CheckForkStatus_Before_Get())
                                    {
                                        short shRow = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2));
                                        short shCell = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(2, 2));
                                        short shFloor = short.Parse(CTaskInfo.CurrentTask.GET_LOC.Substring(4, 2));
                                        AGVForkSendCode(shRow, shCell, shFloor, 2);
                                        AddListBak("取货任务下发完成,取货货位:" + CTaskInfo.CurrentTask.GET_LOC);

                                        CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                    }
                                }
                                else if (cTaskStatus.Task_Status == 4)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "取货完成";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    if (!CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv)
                                    {
                                        if (CTaskInfo.WareName == "XA")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add("L0000C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }
                                        else if (CTaskInfo.WareName == "XJ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add("L0000C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }
                                        else if (CTaskInfo.WareName == "HY")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            listInputKey.Add("three_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add("L0000C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
                                        }
                                        else if (CTaskInfo.WareName == "ZN")
                                        {

                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));

                                        }
                                        else if (CTaskInfo.WareName == "HGZ")
                                        {
                                            List<string> listInputKey = new List<string>();
                                            listInputKey.Add("from_site");
                                            listInputKey.Add("des_site");
                                            List<string> listInputValue = new List<string>();
                                            listInputValue.Add("L" + CTaskInfo.CurrentTask.GET_LOC.Substring(0, 2) + "00C");
                                            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                                            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));

                                        }
                                        AddListBak("取货完成,给AGV下发放货行走任务");

                                        CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));

                                    }
                                    if (CheckForkStatus_Before_Move_Set())
                                    {
                                        short shRow = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2));
                                        short shCell = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(2, 2));
                                        short shFloor = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(4, 2));
                                        AGVForkSendCode(shRow, shCell, shFloor, 1);
                                        AddListBak("放货前货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.SET_LOC);

                                        CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = true;
                                    }
                                }
                                else if (cTaskStatus.Task_Status == 5)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "放货行走中";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));

                                }
                                else if (cTaskStatus.Task_Status == 6)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "到达放货位";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    if (CheckForkStatus_Before_Set())
                                    {
                                        short shRow = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(0, 2));
                                        short shCell = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(2, 2));
                                        short shFloor = short.Parse(CTaskInfo.CurrentTask.SET_LOC.Substring(4, 2));
                                        AGVForkSendCode(shRow, shCell, shFloor, 3);
                                        AddListBak("放货任务下发完成,放货货位:" + CTaskInfo.CurrentTask.SET_LOC);

                                        CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = true;
                                        CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));
                                    }
                                }
                                else if (cTaskStatus.Task_Status == 7)
                                {
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "放货完成";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));

                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 8);
                                    AddListBak("AGV放货完成");

                                    Thread.Sleep(1000);
                                }
                                else if (cTaskStatus.Task_Status == 8)
                                {
                                    #region 任务完成
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "任务完成";
                                        lbTaskStatus.BackColor = Color.Lime;
                                    }));

                                    CTaskInfo.AddToWcsSendDataList(0x02, 0x01, Convert.ToByte(cTaskStatus.Task_Status));

                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 9);
                                    AddListBak("AGV任务执行完成");

                                    CTaskInfo.IsHasTask = false;
                                    FlushPage();
                                    CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = false;
                                    CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = false;
                                    CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = false;
                                    CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = false;

                                    CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = false;
                                    CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv = false;
                                    CTaskInfo.Check_MoveToGetLoc_SendedToAgv = false;

                                    AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
                                    #endregion

                                }
                            }
                        }
                        else
                        {
                            AddListBak("接收到任务信息,但是任务单号为空!");
                        }
                    }
                    else
                    {
                        CTaskInfo.IsHasTask = false;
                        FlushPage();
                    }

                    //---------------------------------end----------------------------------//

                }
                catch (Exception exc)
                {
                    AddListBak("系统控制线程数据处理错误," + exc.Message + exc.StackTrace);
                }

                Thread.Sleep(300);
            }
        }
        #endregion

        #region WCS串口交互控制

        private void InitCom()
        {

            try
            {
                string lineComInfo = iniFile.IniReadValue("COMSET", "WCSCOMINFO");
                string lineComName = "COM1";
                int lineComPort = 9600;
                try
                {
                    lineComName = lineComInfo.Split(',')[0];
                    lineComPort = int.Parse(lineComInfo.Split(',')[1]);
                }
                catch { }

                serialPortWcs.PortName = lineComName;  
                serialPortWcs.BaudRate = lineComPort;
                serialPortWcs.DataBits = 8;
                serialPortWcs.StopBits = System.IO.Ports.StopBits.One;
                serialPortWcs.Parity = System.IO.Ports.Parity.None;
                
                serialPortWcs.Open();
                serialPortWcs.DataReceived += SerialPortWcs_DataReceived;



                InitWcsComFlag = 1;
                lbWcsLinkStatus.Invoke(new EventHandler(delegate {
                    lbWcsLinkStatus.Text = "已连接";
                    lbWcsLinkStatus.BackColor = Color.Lime;
                }));


                AddListBak("WCS串口连接成功");
            }
            catch (Exception s)
            {
                AddListBak("打开远程无线串口串口异常：" + s.Message);

                lbWcsLinkStatus.Invoke(new EventHandler(delegate {
                    lbWcsLinkStatus.Text = "未连接";
                    lbWcsLinkStatus.BackColor = Color.Red;
                }));
            }

            try
            {
                string sReadTemp = iniFile.IniReadValue("PLC_SRM1", "IP");
                string PLC_DQG_IP = string.IsNullOrWhiteSpace(sReadTemp) ? "192.168.0.8" : sReadTemp;
                sReadTemp = iniFile.IniReadValue("PLC_SRM1", "Port");
                string PLC_DQG_Port = string.IsNullOrWhiteSpace(sReadTemp) ? "102" : sReadTemp;
                sReadTemp = iniFile.IniReadValue("PLC_SRM1", "Rack");
                string PLC_DQG_Rack = string.IsNullOrWhiteSpace(sReadTemp) ? "0" : sReadTemp;
                sReadTemp = iniFile.IniReadValue("PLC_SRM1", "Slot");
                string PLC_DQG_Slot = string.IsNullOrWhiteSpace(sReadTemp) ? "1" : sReadTemp;

                PLCMsgModel plcmm = plcSRM1.PLCInit(PLC_DQG_IP, PLC_DQG_Port, PLC_DQG_Rack, PLC_DQG_Slot);
                if (plcmm.Code == 1)
                {
                    //初始化连接成功
                    AddListBak("货叉PLC连接成功！");
                    InitSRM1ComFlag = 1;

                    AddToPLCSRMDataList(cTaskStatus.SRM_RemoteAuto_ToPlc_Addr, 1, 1, 1, 1);
                }
                else
                {
                    AddListBak("货叉PLC连接失败！"+plcmm.Msg);
                }
            }
            catch (Exception ex)
            {
                AddListBak("货叉PLC连接异常！" + ex.Message);
            }

        }



        /// <summary>
        /// 射频门串口发送处理线程
        /// </summary>
        private void UnitSPSendData()
        {
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;
                try
                {
                    if ((sendSPMDataTimeout > 200) || (sendSPMRecvFlag == 0x01))
                    {
                        //通信检测，超过5次后清零
                        if (sendSPMRecvFlag == 0x01)
                        {
                            SPMLinkFlag = 0x01;
                            SPMTime = 0;
                        }
                        else
                        {
                            if (SPMTime >= 5)
                            {
                                SPMLinkFlag = 0x00;
                                SPMTime = 0;
                            }
                        }
                        SPMTime++;
                        if (CTaskInfo.WcsComSendDataList.Count > 0)
                        {
                            byte[] bSendBytes = CTaskInfo.WcsComSendDataList[0];
                            SendSPData(bSendBytes);
                            Thread.Sleep(1000);
                        }
                        sendSPMDataTimeout = 0;
                    }
                    sendSPMDataTimeout++;

                }
                catch (Exception s)
                {
                }

            }
        }

        /// <summary>
        /// 与射频门PLC串口通讯发送数据函数
        /// </summary>
        /// <param name="data"></param>
        private void SendSPData(byte[] data)
        {
            if (data == null) return;
            int tmpLen = 0;
            tmpLen = data.Length;
            if (tmpLen < 100)
            {
                if (serialPortWcs.IsOpen)
                {
                    LogWcsInfo.Debug("AGV-Send:" + ToHexStrFromByte(data));
                    //发送
                    serialPortWcs.Write(data, 0, tmpLen);
                }
            }
        }
        /// <summary>
        /// 字节数组转16进制字符串：空格分隔
        /// </summary>
        /// <param name="byteDatas"></param>
        /// <returns></returns>
        public string ToHexStrFromByte( byte[] byteDatas)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < byteDatas.Length; i++)
            {
                builder.Append(string.Format("{0:X2} ", byteDatas[i]));
            }
            return builder.ToString().Trim();
        }
        object obj = new object();
        private void SerialPortWcs_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

            int m;
            int tmplen = 0;
            byte[] tmpRecv = new byte[256];

            try
            {
                lock (obj)
                {
                    //接收字符串
                    tmplen = serialPortWcs.Read(tmpRecv, 0, 256);
                    if (tmplen > 0)
                    {
                        //LogWcsInfo.Debug("AGV-Receive1:" + ToHexStrFromByte(tmpRecv)); 
                        if (tmplen + recvSPMLen >= 256) recvSPMLen = 0;
                        for (m = 0; m < tmplen; m++)
                        {
                            recvSPMData[recvSPMLen++] = tmpRecv[m];
                        }
                        //   Release the Mutex.
                        //mut.ReleaseMutex();
                    }
                }
            }
            catch (Exception s)
            {
            }
        }

        /// <summary>
        /// 射频门串口读取线程
        /// </summary>
        private void UnitSPRecvData()
        {
            int ret;
            int tmpFrameLen = 0;
            byte[] tmpFrameData = new byte[32];
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;
                //
                //接收数据解析
                if (recvSPMLen >= 7)
                {
                    try
                    {
                        //获取数据解析
                        // Wait until it is safe to enter.
                        //mut.WaitOne();
                        ret = GetFrameSPM(ref recvSPMData, ref recvSPMLen, ref tmpFrameData, ref tmpFrameLen);

                        if (ret == 0)
                        {
                            LogWcsInfo.Debug("AGV-Rece:" + ToHexStrFromByte(tmpFrameData));
                            //显示
                            if (tmpFrameData[0] == 0x7E && tmpFrameData[1] == 0x02 && (tmpFrameData[2] == 0x01 || tmpFrameData[2] == 0x02 || tmpFrameData[2] == 0x03) && tmpFrameData[6] == 0x68)
                            {
                                //任务上报或者故障后的接收WCS的返回值
                                //接收到发送给WCS的返回值时，删除本地发送列表，不再继续发送给WCS
                                byte[] btemp = new byte[7];
                                for (int i = CTaskInfo.WcsComSendDataList.Count - 1; i >= 0; i--)
                                {
                                    byte[] bTemp = CTaskInfo.WcsComSendDataList[i];

                                    if (bTemp[0] == 0x7E && bTemp[1] == 0x02 && (bTemp[2] == 0x01 || bTemp[2] == 0x02 || bTemp[2] == 0x03) && bTemp[4] == tmpFrameData[4])
                                    {
                                        CTaskInfo.WcsComSendDataList.RemoveAt(i);
                                    }
                                }
                            }
                            if (tmpFrameData[0] == 0x7E && tmpFrameData[1] == 0x02 && tmpFrameData[2] == 0x00 && tmpFrameData[6] == 0x68)
                            {
                                //发送给WCS的心跳包后，接收到WCS的心跳返回值
                                //接收到发送给WCS的返回值时，删除本地发送列表，不再继续发送给WCS
                                byte[] btemp = new byte[7];
                                for (int i = CTaskInfo.WcsComSendDataList.Count - 1; i >= 0; i--)
                                {
                                    byte[] bTemp = CTaskInfo.WcsComSendDataList[i];

                                    if (bTemp[0] == 0x7E && bTemp[1] == 0x02 && bTemp[2] == 0X00 )
                                    {
                                        CTaskInfo.WcsComSendDataList.RemoveAt(i);
                                    }
                                }
                                if (tmpFrameData[2] == 0x00)
                                {
                                    //AddListBak("接收WCS的心跳包返回值");
                                    lbWcsLinkStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbWcsLinkStatus.BackColor = Color.Lime;
                                    }));
                                }
                            }
                            else if (tmpFrameData[0] == 0x7E && tmpFrameData[1] == 0x01 && (tmpFrameData[2] == 0x00 || tmpFrameData[2] == 0x01 || tmpFrameData[2] == 0x02))
                            {
                                if (tmpFrameData[2] == 0x01)
                                {
                                    //接收到新任务
                                    byte len = tmpFrameData[3];
                                    byte[] bTask = new byte[len];
                                    for (int i = 0; i < len; i++)
                                    {
                                        bTask[i] = tmpFrameData[i + 4];
                                    }

                                    string strReceiveNewTask = Encoding.Default.GetString(bTask);
                                    string[] cell = strReceiveNewTask.Split('|');
                                    UYD_WCS.Model.W_TASK_AGV modelTaskAgv = new UYD_WCS.Model.W_TASK_AGV();
                                    modelTaskAgv.TASK_FLAG = cell[0];
                                    modelTaskAgv.GET_LOC = cell[1];
                                    modelTaskAgv.SET_LOC = cell[2];
                                    modelTaskAgv.TASK_NO = cell[3];
                                    modelTaskAgv.TASK_DATE = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    string strWhere = " TASK_NO='" + modelTaskAgv.TASK_NO + "' AND GET_LOC='" + modelTaskAgv.GET_LOC + "' AND SET_LOC='" + modelTaskAgv.SET_LOC + "' ";
                                    if (!bllTaskAgv.Exists(strWhere))
                                    {
                                        modelTaskAgv.TASK_ID = bllTaskAgv.GetMaxID();
                                        modelTaskAgv.TASK_STATUS_CODE = 1;
                                        bllTaskAgv.Add(modelTaskAgv);
                                        AddListBak("接收到新任务,存储成功!任务号:" + modelTaskAgv.TASK_NO + "取货货位:" + modelTaskAgv.GET_LOC + "放货货位:" + modelTaskAgv.SET_LOC);
                                    }
                                    else
                                    {
                                        AddListBak("接收到新任务,存储成功!但是任务重复！任务:" + strReceiveNewTask);
                                    }

                                    //string strReceiveNewTask = Encoding.Default.GetString(bTask);

                                    //AddListBak("接收到新任务，" + strReceiveNewTask);
                                    //UYD_WCS.Model.W_TASK_AGV modelTaskAgv = Newtonsoft.Json.JsonConvert.DeserializeObject<UYD_WCS.Model.W_TASK_AGV>(strReceiveNewTask);
                                    //string strWhere = " TASK_NO='" + modelTaskAgv.TASK_NO + "' AND GET_LOC='" + modelTaskAgv.GET_LOC + "' AND SET_LOC='" + modelTaskAgv.SET_LOC + "' ";
                                    //if (!bllTaskAgv.Exists(strWhere))
                                    //{
                                    //    modelTaskAgv.TASK_ID = bllTaskAgv.GetMaxID();
                                    //    modelTaskAgv.TASK_STATUS_CODE = 1;
                                    //    bllTaskAgv.Add(modelTaskAgv);
                                    //    AddListBak("接收到新任务,存储成功!" + strReceiveNewTask);
                                    //}
                                }
                                else if (tmpFrameData[2] == 0x02)
                                {
                                    //任务取消新任务
                                    byte len = tmpFrameData[3];
                                    byte[] bTask = new byte[len];
                                    for (int i = 0; i < len; i++)
                                    {
                                        bTask[i] = tmpFrameData[i + 4];
                                    }
                                    cTaskStatus.ReceiveTaskCancle = Encoding.Default.GetString(bTask);
                                }
                                //任务接收后的返回
                                #region 给WCS发送返回值,WCS接收到后不再继续发送
                                byte[] b = new byte[] { 0x7E, 0x01, tmpFrameData[2], 0x01, 0x00 };
                                int sum = 0;
                                for (int i = 0; i < b.Length; i++)
                                {
                                    sum += b[i];
                                }
                                byte[] bSend = new byte[] { 0x7E, 0x01, tmpFrameData[2], 0x01, 0x00, (byte)sum, 0x68 };
                                SendSPData(bSend);
                                #endregion
                            }

                            serialPortWcs.DiscardInBuffer();
                            recvSPMData = new byte[1000];
                            recvSPMLen = 0;
                            sendSPMRecvFlag = 0x01;
                        }
                    }
                    catch (Exception s)
                    {
                    }
                }
                Thread.Sleep(100);
            }
        }

        /// <summary>
        /// 射频门数据验证
        /// </summary>
        /// <param name="recvData"></param>
        /// <param name="recvLen"></param>
        /// <param name="tmpFrame"></param>
        /// <param name="tmpLen"></param>
        /// <returns></returns>
        private int GetFrameSPM(ref byte[] recvData, ref int recvLen, ref byte[] tmpFrame, ref int tmpLen)
        {
            int n;
            int m;
            byte crc1;
            byte crc2;
            int dataLen;
            bool flag = false;
            int eIndex = 0;
            //
            byte[] tmpdata = new byte[10];
            //
            if (recvSPMLen >= 7)
            {
                //find
                for (n = 0; n < recvSPMLen; n++)
                {
                    if (recvSPMData[n] == 0x7E && recvSPMData[n + 1] == 0x02 && recvSPMData[n + 6] == 0x68)
                    {
                        tmpFrame = new byte[7];
                        for (m = n; m < 7; m++) tmpFrame[m - n] = recvSPMData[n + m];
                        eIndex = n + 7;
                        flag = true;
                        break;
                    }
                    else if (recvSPMData[n] == 0x7E && recvSPMData[n + 1] == 0x01 && recvSPMData[n + 2] == 0x00 && recvSPMData[n + 6] == 0x68)
                    {
                        //wcs心跳包数据
                        tmpFrame = new byte[7];
                        for (m = n; m < 7; m++) tmpFrame[m - n] = recvSPMData[n + m];
                        eIndex = n + 7;
                        flag = true;
                        break;
                    }
                    else if (recvSPMData[n] == 0x7E && recvSPMData[n + 1] == 0x01 && (recvSPMData[n + 2] == 0x01 || recvSPMData[n + 2] == 0x02))
                    {
                        //任务接收或者任务取消的包数据
                        dataLen = recvSPMData[n + 3];
                        if (recvSPMData[n + 3 + dataLen + 2] == 0x68)
                        {
                            tmpFrame = new byte[3 + dataLen + 2 + 1];
                            for (m = 0; m < 3 + dataLen + 2 + 1; m++)
                                tmpFrame[m] = recvSPMData[m + n];

                            eIndex = n + 3 + dataLen + 2 + 1;
                            flag = true;
                            break;
                        }
                    }
                    if (flag) break;
                }
                if (flag)
                {
                    //把后面数据移到前面
                    for (n = eIndex; n < recvSPMLen; n++)
                    {
                        recvSPMData[n - eIndex] = recvSPMData[n];
                    }
                    recvSPMLen -= eIndex;
                    if (recvSPMLen <= 0)
                    {
                        recvSPMLen = 0;
                    }

                    return 0;
                }
            }
            return 1;
        }


        #endregion

        #region 货叉控制线程

        /// <summary>
        /// 添加到List
        /// </summary>
        /// <param name="addr">地址</param>
        /// <param name="ReadOrWrite">读取或者写入 Read:0 Write:1</param>
        /// <param name="val">具体值</param>
        /// <param name="valType">值类型 bool:0  short:1</param>
        /// <param name="arrayLen">读取的数据长度</param>
        private void AddToPLCSRMDataList(string addr, short ReadOrWrite, object val, short valType, ushort arrayLen)
        {
            CTaskInfo.PLCSRMWirteDataList.Add(new Smart200Data
            {
                addr = addr,
                val = val,
                valtype = valType,
                read = ReadOrWrite,
                arraylen = arrayLen
            });
        }

        /// <summary>
        /// 堆垛机1读取指令下发
        /// </summary>
        private void UnitPLCSRM_Read()
        {
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;

                try
                {
                    if (CTaskInfo.PLCSRMWirteDataList.Count > 0)
                    {
                        Thread.Sleep(10);
                        continue;
                    }
                    //判断是否有其它信息发送
                    if (CTaskInfo.PLCSRMReadDataList.Count > 0)
                    {
                        PLCMsgModel plcMM = new PLCMsgModel();
                        Smart200Data senddata = CTaskInfo.PLCSRMReadDataList[0];

                        if (senddata.read == 0)
                        {
                            //读取
                            if (senddata.valtype == 0)
                            {
                                plcMM = plcSRM1.PLCReadBool(senddata.addr);
                                //读取bool值
                                if (plcMM.Code == 1)
                                {
                                    if (plcMM.Val == null) continue;
                                    bool bRead = (bool)plcMM.Val;

                                    if (senddata.addr == cTaskStatus.SRM_Hearbeat_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Heartbeat = bRead ? 1 : 0;

                                        if (cTaskStatus.SRM_Heartbeat == 1)
                                        {
                                            lbForkHearbeat.Invoke(new EventHandler(delegate
                                            {
                                                lbForkHearbeat.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Heartbeat == 0)
                                        {
                                            lbForkHearbeat.Invoke(new EventHandler(delegate
                                            {
                                                lbForkHearbeat.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_RemoteAuto_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_RemoteAuto = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_RemoteAuto == 1)
                                        {
                                            lbForkRemoteAuto.Invoke(new EventHandler(delegate
                                            {
                                                lbForkRemoteAuto.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_RemoteAuto == 0)
                                        {
                                            lbForkRemoteAuto.Invoke(new EventHandler(delegate
                                            {
                                                lbForkRemoteAuto.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Alarm_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Alarm = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_Alarm == 1)
                                        {
                                            lbForkAlarm.Invoke(new EventHandler(delegate
                                            {
                                                lbForkAlarm.BackColor = Color.Red;
                                            }));

                                            lbForkAlarmInfo.Invoke(new EventHandler(delegate
                                            {
                                                lbForkAlarmInfo.BackColor = Color.Red;
                                                lbForkAlarmInfo.Text = cTaskStatus.SRM_BreakDownInfo.ToString();
                                            }));

                                        }
                                        else if (cTaskStatus.SRM_Alarm == 0)
                                        {
                                            lbForkAlarm.Invoke(new EventHandler(delegate
                                            {
                                                lbForkAlarm.BackColor = Color.LightSteelBlue;
                                            }));

                                            lbForkAlarmInfo.Invoke(new EventHandler(delegate
                                            {
                                                lbForkAlarmInfo.BackColor = Color.LightSteelBlue;
                                                lbForkAlarmInfo.Text = "无";
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_ForkIsHasGoods_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_ForkIsHasGood = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_ForkIsHasGood == 1)
                                        {
                                            lbForkHasGoods.Invoke(new EventHandler(delegate
                                            {
                                                lbForkHasGoods.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_ForkIsHasGood == 0)
                                        {
                                            lbForkHasGoods.Invoke(new EventHandler(delegate
                                            {
                                                lbForkHasGoods.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_ForkInZero_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_ForkInZero = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_ForkInZero == 1)
                                        {
                                            lbForkInZero.Invoke(new EventHandler(delegate
                                            {
                                                lbForkInZero.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_ForkInZero == 0)
                                        {
                                            lbForkInZero.Invoke(new EventHandler(delegate
                                            {
                                                lbForkInZero.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Task_Finished_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Task_Finish = bRead ? 1 : 0;

                                        if (cTaskStatus.SRM_Task_Finish == 1)
                                        {
                                            lbForkTaskFinished.Invoke(new EventHandler(delegate
                                            {
                                                lbForkTaskFinished.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Task_Finish == 0)
                                        {
                                            lbForkTaskFinished.Invoke(new EventHandler(delegate
                                            {
                                                lbForkTaskFinished.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                        AddListBak_Fork("货叉PLC读取任务完成:" + senddata.addr + "=" + (bRead ? "1" : "0"));
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Get_Finished_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Get_Finish = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_Get_Finish == 1)
                                        {
                                            lbForkGetFinished.Invoke(new EventHandler(delegate
                                            {
                                                lbForkGetFinished.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Get_Finish == 0)
                                        {
                                            lbForkGetFinished.Invoke(new EventHandler(delegate
                                            {
                                                lbForkGetFinished.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Set_Finished_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Set_Finish = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_Set_Finish == 1)
                                        {
                                            lbForkSetFinished.Invoke(new EventHandler(delegate
                                            {
                                                lbForkSetFinished.BackColor = Color.Lime;

                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Set_Finish == 0)
                                        {
                                            lbForkSetFinished.Invoke(new EventHandler(delegate
                                            {
                                                lbForkSetFinished.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    CTaskInfo.PLCSRMReadDataList.RemoveAt(0);

                                    AddListBak_Fork("货叉PLC读取 :" + senddata.addr + "=" + (bRead ? "1" : "0"));
                                }
                            }
                            else if (senddata.valtype == 1)
                            {
                                plcMM = plcSRM1.PLCReadByte(senddata.addr);
                                //读取short值
                                if (plcMM.Code == 1)
                                {
                                    if (plcMM.Val == null) continue;
                                    short bRead = (short)(plcMM.Val);
                                    CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                }
                            }
                            else if (senddata.valtype == 2)
                            {
                                plcMM = plcSRM1.PLCReadInt(senddata.addr);
                                //读取int值
                                if (plcMM.Code == 1)
                                {
                                    if (plcMM.Val == null) continue;
                                    object objBreakdown = plcMM.Val;
                                    CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                }
                            }
                            else if (senddata.valtype == 3)
                            {
                                if (senddata.arraylen > 0)
                                {
                                    plcMM = plcSRM1.PLCReadBoolArray(senddata.addr, senddata.arraylen);
                                    if (plcMM.Code == 1)
                                    {
                                        if (plcMM.Val == null) continue;
                                        CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                    }
                                }
                            }
                            else if (senddata.valtype == 4)
                            {
                                if (senddata.arraylen > 0)
                                {
                                    plcMM = plcSRM1.PLCReadByte(senddata.addr, senddata.arraylen);
                                    if (plcMM.Code == 1)
                                    {
                                        if (plcMM.Val == null) continue;
                                        short[] bRead = (short[])plcMM.Val;
                                        if (senddata.addr == cTaskStatus.SRM_AlarmCode_ToWcs_Addr)
                                        {
                                            cTaskStatus.SRM_BreakDownInfo = bRead[0];
                                            cTaskStatus.SRM_Status = bRead[1];
                                            cTaskStatus.SRM_Pos_Row = bRead[2];
                                            cTaskStatus.SRM_Pos_Floor = bRead[3];


                                            if (cTaskStatus.SRM_Status == 1)
                                            {
                                                lbForkStatus.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkStatus.BackColor = Color.Lime;
                                                    lbForkStatus.Text = "运行";
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Status == 0)
                                            {
                                                lbForkStatus.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkStatus.BackColor = Color.LightSteelBlue;
                                                    lbForkStatus.Text = "空闲";
                                                }));
                                            }

                                            if (cTaskStatus.SRM_Pos_Row > 0)
                                            {
                                                lbForkPosRow.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkPosRow.BackColor = Color.Lime;
                                                    lbForkPosRow.Text = cTaskStatus.SRM_Pos_Row.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Pos_Row == 0)
                                            {
                                                lbForkPosRow.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkPosRow.BackColor = Color.LightSteelBlue;
                                                    lbForkPosRow.Text = "0";
                                                }));
                                            }
                                            if (cTaskStatus.SRM_Pos_Floor > 0)
                                            {
                                                lbForkPosFloor.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkPosFloor.BackColor = Color.Lime;
                                                    lbForkPosFloor.Text = cTaskStatus.SRM_Pos_Floor.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Pos_Row == 0)
                                            {
                                                lbForkPosFloor.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkPosFloor.BackColor = Color.LightSteelBlue;
                                                    lbForkPosFloor.Text = "0";
                                                }));
                                            }
                                        }
                                        else if (senddata.addr == cTaskStatus.SRM_TaskID_ToWcs_Addr)
                                        {
                                            cTaskStatus.SRM_Task_ID = bRead[0];

                                            cTaskStatus.SRM_GetGoodsApply = bRead[3];
                                            cTaskStatus.SRM_SetGoodsApply = bRead[4];

                                            if (cTaskStatus.SRM_Task_ID > 0)
                                            {
                                                lbForkTaskID.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkTaskID.BackColor = Color.Lime;
                                                    lbForkTaskID.Text = cTaskStatus.SRM_Task_ID.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Task_ID == 0)
                                            {
                                                lbForkTaskID.Invoke(new EventHandler(delegate
                                                {
                                                    lbForkTaskID.BackColor = Color.LightSteelBlue;
                                                    lbForkTaskID.Text = "0";
                                                }));
                                            }



                                            if (cTaskStatus.SRM_GetGoodsApply > 0)
                                            {
                                                lbGetGoodsApply.Invoke(new EventHandler(delegate
                                                {
                                                    lbGetGoodsApply.BackColor = Color.Lime;
                                                    lbGetGoodsApply.Text = cTaskStatus.SRM_Task_ID.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_GetGoodsApply == 0)
                                            {
                                                lbGetGoodsApply.Invoke(new EventHandler(delegate
                                                {
                                                    lbGetGoodsApply.BackColor = Color.LightSteelBlue;
                                                    lbGetGoodsApply.Text = "0";
                                                }));
                                            }
                                            if (cTaskStatus.SRM_SetGoodsApply > 0)
                                            {
                                                lbSetGoodsApply.Invoke(new EventHandler(delegate
                                                {
                                                    lbSetGoodsApply.BackColor = Color.Lime;
                                                    lbSetGoodsApply.Text = cTaskStatus.SRM_Task_ID.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_SetGoodsApply == 0)
                                            {
                                                lbSetGoodsApply.Invoke(new EventHandler(delegate
                                                {
                                                    lbSetGoodsApply.BackColor = Color.LightSteelBlue;
                                                    lbSetGoodsApply.Text = "0";
                                                }));
                                            }
                                        }
                                        CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Smart200Data tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Hearbeat_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Get_Finished_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Set_Finished_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_RemoteAuto_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Alarm_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Task_Finished_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_ForkIsHasGoods_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_ForkInZero_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_AlarmCode_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 4;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 4;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);

                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_TaskID_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 4;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 5;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                    }

                    //---------------------------------end----------------------------------//
                }
                catch (Exception s)
                {
                    AddListBak("货叉PLC读取线程异常:" + s.Message + s.StackTrace);
                }
                Thread.Sleep(50);
            }
        }

        /// <summary>
        /// 产线写入指令下发
        /// </summary>
        private void UnitPLCSRM_Write()
        {
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;

                try
                {
                    //-------------------------------发送数据--------------------------------//
                    //判断是否有其它信息发送
                    if (CTaskInfo.PLCSRMWirteDataList.Count > 0)
                    {
                        PLCMsgModel plcMM = new PLCMsgModel();
                        Smart200Data senddata = CTaskInfo.PLCSRMWirteDataList[0];

                        AddListBak_Fork("货叉PLC写入 :" + senddata.addr+"="+senddata.val.ToString());
                        if (senddata.read == 0)
                        {
                            //读取
                        }
                        else if (senddata.read == 1)
                        {
                            bool blSendValue = false;
                            short shSendValue = 0;
                            //写入
                            if (senddata.valtype == 0)
                            {
                                blSendValue = Convert.ToInt16(senddata.val) == 1 ? true : false;
                                plcMM = plcSRM1.PLCWrite(senddata.addr, blSendValue);
                                //读取short值
                                if (plcMM.Code == 1)
                                {
                                    CTaskInfo.PLCSRMWirteDataList.RemoveAt(0);
                                }
                            }
                            else if (senddata.valtype == 1)
                            {
                                shSendValue = Convert.ToInt16(senddata.val);
                                plcMM = plcSRM1.PLCWrite(senddata.addr, shSendValue);
                                //读取short值
                                if (plcMM.Code == 1)
                                {
                                    CTaskInfo.PLCSRMWirteDataList.RemoveAt(0);
                                }
                            }
                        }
                    }

                    //---------------------------------end----------------------------------//
                }
                catch (Exception s)
                {
                    AddListBak("货叉写入线程异常:" + s.Message);
                }
                Thread.Sleep(100);
            }
        }
        #endregion

        #region 后台获取任务单号线程
        /// <summary>
        /// 当前无任务执行时，每隔10秒钟去后台获取一次任务单号
        /// </summary>
        private void InitializeBackgroundWorker()
        {
            try
            {
                string sTaskGetDelay = iniFile.IniReadValue("TaskInfo", "GetDelay");
                CTaskInfo.TaskGetDelay = sTaskGetDelay == "" ? 10 : int.Parse(sTaskGetDelay);
                bgGetTask.WorkerReportsProgress = true;
                bgGetTask.WorkerSupportsCancellation = true;
                bgGetTask.DoWork += new DoWorkEventHandler(bgGetTask_DoWork);
            }
            catch (Exception exc)
            {
                AddListBak("获取任务单号配置异常，请检查配置文件");
            }
        }
        private void FlushPage()
        {
            lbTaskStatus.Invoke(new EventHandler(delegate
            {
                lbTaskStatus.Text = "空闲";
                lbTaskStatus.BackColor = Color.Yellow;
            }));
            lbTaskFlag.Invoke(new EventHandler(delegate {
                lbTaskFlag.Text = "";
            }));
            lbTaskNo.Invoke(new EventHandler(delegate {
                lbTaskNo.Text = "";
            }));
            lbTaskDateTime.Invoke(new EventHandler(delegate {
                lbTaskDateTime.Text = "";
            }));
            lbTaskGetLoc.Invoke(new EventHandler(delegate {
                lbTaskGetLoc.Text = "";
            }));
            lbTaskSetLoc.Invoke(new EventHandler(delegate {
                lbTaskSetLoc.Text = "";
            }));
        }
        /// <summary>
        /// 后台实时检查是否有新的任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgGetTask_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                //if (allThreadValue == 1) break;
                if (bgGetTask.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
                try
                {
                    if (!CTaskInfo.IsHasTask)
                    {
                        #region 当日历史任务清单 
                        string strWhere = " TASK_STATUS_CODE<9 ";
                        CTaskInfo.CurrentTask = bllTaskAgv.GetModel(strWhere);
                        if (CTaskInfo.CurrentTask != null)
                            if (!string.IsNullOrEmpty(CTaskInfo.CurrentTask.TASK_NO))
                            {
                                CTaskInfo.IsHasTask = true;
                            }
                        if (CTaskInfo.IsHasTask)
                        {
                            switch (CTaskInfo.CurrentTask.TASK_STATUS_CODE)
                            {
                                case 0:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "空闲";
                                    }));
                                    break;
                                case 1:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "待执行";
                                    }));
                                    break;
                                case 2:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "取货行走中";
                                    }));
                                    break;
                                case 3:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "到达取货位";
                                    }));
                                    break;
                                case 4:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "取货完成";
                                    }));
                                    break;
                                case 5:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "放货行走中";
                                    }));
                                    break;
                                case 6:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "到达放货位";
                                    }));
                                    break;
                                case 7:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "放货完成";
                                    }));
                                    break;
                                case 8:
                                    lbTaskStatus.Invoke(new EventHandler(delegate
                                    {
                                        lbTaskStatus.Text = "任务完成";
                                    }));
                                    break;
                            }

                            cTaskStatus.Task_Status = (int)CTaskInfo.CurrentTask.TASK_STATUS_CODE;

                            lbTaskFlag.Invoke(new EventHandler(delegate {
                                if (CTaskInfo.CurrentTask.TASK_FLAG == "02")
                                    lbTaskFlag.Text = "入库";
                                else if (CTaskInfo.CurrentTask.TASK_FLAG == "01")
                                    lbTaskFlag.Text = "出库";
                                else if (CTaskInfo.CurrentTask.TASK_FLAG == "03")
                                    lbTaskFlag.Text = "盘库";
                            }));

                            lbTaskNo.Invoke(new EventHandler(delegate {
                                lbTaskNo.Text = CTaskInfo.CurrentTask.TASK_NO;
                            }));
                            lbTaskDateTime.Invoke(new EventHandler(delegate {
                                lbTaskDateTime.Text = CTaskInfo.CurrentTask.TASK_DATE;
                            }));
                            lbTaskGetLoc.Invoke(new EventHandler(delegate {
                                lbTaskGetLoc.Text = CTaskInfo.CurrentTask.GET_LOC;
                            }));
                            lbTaskSetLoc.Invoke(new EventHandler(delegate {
                                lbTaskSetLoc.Text = CTaskInfo.CurrentTask.SET_LOC;
                            }));
                        }
                        else
                        {
                            lbTaskStatus.Invoke(new EventHandler(delegate
                            {
                                lbTaskStatus.Text = "空闲";
                                lbTaskStatus.BackColor = Color.Yellow;
                            }));
                            lbTaskFlag.Invoke(new EventHandler(delegate {
                                lbTaskFlag.Text = "";
                            }));
                            lbTaskNo.Invoke(new EventHandler(delegate {
                                lbTaskNo.Text = "";
                            }));
                            lbTaskDateTime.Invoke(new EventHandler(delegate {
                                lbTaskDateTime.Text = "";
                            }));
                            lbTaskGetLoc.Invoke(new EventHandler(delegate {
                                lbTaskGetLoc.Text = "";
                            }));
                            lbTaskSetLoc.Invoke(new EventHandler(delegate {
                                lbTaskSetLoc.Text = "";
                            }));
                        }
                        #endregion
                    }

                    Thread.Sleep(CTaskInfo.TaskGetDelay * 1000);
                }
                catch (Exception exc)
                {
                    AddListBak("获取任务单号及任务明细时出现异常" + exc.Message + "\r\n" + exc.StackTrace);
                }
            }
        }

        #endregion

        #region 初始化变量
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        private void InitGlobalVariable()
        {
            #region 读取配置文件 
            try
            {
                CTaskInfo.AGV_URL = iniFile.IniReadValue("SysInfo", "AGV_URL") == "" ? "" : iniFile.IniReadValue("SysInfo", "AGV_URL");
                CTaskInfo.AgvGetSetPointLoc = iniFile.IniReadValue("SysInfo", "Agv_GetSetPointLoc") == "" ? "" : iniFile.IniReadValue("SysInfo", "Agv_GetSetPointLoc");
                CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo") == "" ? "" : iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
                CTaskInfo.WareName = iniFile.IniReadValue("SysInfo", "WareName"); 
                CTaskInfo.AgvAutoChangeLowValue = iniFile.IniReadValue("SysInfo", "AgvAutoChangeLowValue");
            }
            catch (Exception exc)
            {
                AddListBak("获取系统配置异常，请检查系统配置文件");
            }
            #endregion
        }
        #endregion

        #region 日志存储

        log4net.ILog logSysRun = log4net.LogManager.GetLogger("LogSysRun"); //Logging 名字要在 App.config 中能找到
        //跨线程访问listbox控件
        delegate void AddList();
        private void AddListBak(string s)
        {
            // 将委托实例化 
            AddList a = delegate ()
            {
                if (listBoxSysRunLog.Items.Count > 0)
                {
                    if (listBoxSysRunLog.Items[0].ToString().Split(']')[1] == s) return;
                }
                if (listBoxSysRunLog.Items.Count > 1000) listBoxSysRunLog.Items.Clear();
                listBoxSysRunLog.Items.Insert(0, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + s);
                logSysRun.Info("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]-" + s);
                listBoxSysRunLog.Refresh();
            };
            listBoxSysRunLog.Invoke(a);

        }


        log4net.ILog logAgv = log4net.LogManager.GetLogger("LogAgv"); //Logging 名字要在 App.config 中能找到
        private void AddListBak_Agv(string s)
        {

            tabControl1.Invoke(new EventHandler(delegate {
                if(tabControl1.SelectedIndex==1)
                {
                    if (!s.Contains("percentage"))
                    {
                        listBoxAgvControlLog.Invoke(new EventHandler(delegate
                        {

                            if (listBoxAgvControlLog.Items.Count > 0)
                            {
                                if (listBoxAgvControlLog.Items[0].ToString().Split(']')[1] == s) return;
                            }
                            if (listBoxAgvControlLog.Items.Count > 1000) listBoxAgvControlLog.Items.Clear();
                            listBoxAgvControlLog.Items.Insert(0, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + s);
                            listBoxAgvControlLog.Refresh();

                        }));
                    }
                }
                else
                {
                    if (!s.Contains("percentage"))
                    {
                        // 将委托实例化 
                        AddList a = delegate ()
                        {
                            if (listBoxAgv.Items.Count > 0)
                            {
                                if (listBoxAgv.Items[0].ToString().Split(']')[1] == s) return;
                            }
                            if (listBoxAgv.Items.Count > 1000) listBoxAgv.Items.Clear();
                            listBoxAgv.Items.Insert(0, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + s);
                            listBoxAgv.Refresh();
                        };
                        listBoxAgv.Invoke(a);
                    }
                }
            }));

            try
            {
                if (!s.Contains("percentage"))
                {
                    logAgv.Info("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]-" + s);
                }
            }
            catch
            {

            }
        }


        log4net.ILog logFork = log4net.LogManager.GetLogger("LogFork"); //Logging 名字要在 App.config 中能找到
        private void AddListBak_Fork(string s)
        {
            try
            {
                    logFork.Info("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]-" + s);
                
            }
            catch
            {

            }
        }

        #endregion


        #region AGV操作信息

        private void CTaskStatus_AgvReportTaskStatusChangeEvent(object sender, EventArgs e)
        {
            try
            {
                if(cTaskStatus.Agv_Report_Task_Status == "behavior_exit" || cTaskStatus.Agv_Report_Task_Status == "behavior_preempted")
                {
                    lbAgvStatus.Invoke(new EventHandler(delegate {
                        lbAgvStatus.Text = "空闲";
                        lbAgvStatus.BackColor = Color.Yellow;
                    }));
                    lbAgvDestLoc.Invoke(new EventHandler(delegate {
                        lbAgvDestLoc.Text = "无";
                    }));
                }
                else if(cTaskStatus.Agv_Report_Task_Status.Contains( "going"))
                {
                    lbAgvStatus.Invoke(new EventHandler(delegate {
                        lbAgvStatus.Text = "行走中";
                        lbAgvStatus.BackColor = Color.Lime;
                    }));
                    string strAgvDestLoc = cTaskStatus.Agv_Report_Task_Status.Split('_')[1];
                    lbAgvDestLoc.Invoke(new EventHandler(delegate {
                        lbAgvDestLoc.Text = strAgvDestLoc;
                    }));
                    if (CTaskInfo.IsHasTask)
                    {
                        if (CTaskInfo.CurrentTask.TASK_FLAG == "02")
                        {
                            if (strAgvDestLoc == GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC))
                            {
                                if (cTaskStatus.Task_Status < 3)
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 2);
                            }
                            else if (strAgvDestLoc == GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC))
                            {
                                if (cTaskStatus.Task_Status ==4)
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 5);
                            }
                        }
                        else if (CTaskInfo.CurrentTask.TASK_FLAG == "01")
                        {
                            if (strAgvDestLoc == GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC))
                            {
                                if (cTaskStatus.Task_Status < 3)
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 2);
                            }
                            else if (strAgvDestLoc == GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC))
                            {
                                if (cTaskStatus.Task_Status == 4)
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 5);
                            }
                        }
                    }
                }
                else if (cTaskStatus.Agv_Report_Task_Status.Contains("arrived"))
                {
                    lbAgvStatus.Invoke(new EventHandler(delegate {
                        lbAgvStatus.Text = "到位";
                        lbAgvStatus.BackColor = Color.Lime;
                    }));
                    string strAgvArriveLoc = cTaskStatus.Agv_Report_Task_Status.Split('_')[1];
                    lbAgvDestLoc.Invoke(new EventHandler(delegate {
                        lbAgvDestLoc.Text = strAgvArriveLoc;
                    }));
                    iniFile.IniWriteValue("SysInfo", "AGV_CurrentLocNo", strAgvArriveLoc);
                    if (CTaskInfo.IsHasTask)
                    {
                        if (CTaskInfo.CurrentTask.TASK_FLAG == "02")
                        {
                            if (strAgvArriveLoc == GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC))
                            {
                                if (cTaskStatus.Task_Status < 3)
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 3);
                                else if (cTaskStatus.Task_Status == 7)
                                {
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 8);
                                }
                            }
                            else if (strAgvArriveLoc == GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC))
                            {
                                UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 6);
                            }
                        }
                        else if (CTaskInfo.CurrentTask.TASK_FLAG == "01")
                        {
                            if (strAgvArriveLoc == GetAGVLocNo(CTaskInfo.CurrentTask.GET_LOC))
                            {
                                if (cTaskStatus.Task_Status < 3)
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 3);
                                else if (cTaskStatus.Task_Status == 7)
                                {
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 8);
                                }
                            }
                            else if (strAgvArriveLoc == GetAGVLocNo(CTaskInfo.CurrentTask.SET_LOC))
                            {
                                if (cTaskStatus.Task_Status == 5)
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 6);
                            }
                        }
                    }
                    if(strAgvArriveLoc==CTaskInfo.AgvGetSetPointLoc)
                        cTaskStatus.AgvAutoChange = 0;

                    if (CTaskInfo.WareName == "XJ")
                    {
                        CTaskInfo.AddToWcsSendDataList(0x02, 0x03, getPos(strAgvArriveLoc));
                    }
                }
                else if (cTaskStatus.Agv_Report_Task_Status.Contains("charge_point"))
                {
                    lbAgvStatus.Invoke(new EventHandler(delegate {
                        lbAgvStatus.Text = "到达充电位";
                        lbAgvStatus.BackColor = Color.Lime;
                    }));

                    iniFile.IniWriteValue("SysInfo", "AGV_CurrentLocNo", "charge_point");

                }
                else if (cTaskStatus.Agv_Report_Task_Status.Contains("Judgebattery"))
                {
                    lbAgvStatus.Invoke(new EventHandler(delegate {
                        lbAgvStatus.Text = "充电中";
                        lbAgvStatus.BackColor = Color.Lime;
                    }));
                }
            }
            catch (Exception exc)
            {
                AddListBak("AGV到位后数据处理异常!" + exc.Message + exc.StackTrace);
            }
        }
        private byte getPos(string strAgvArriveLoc)
        {
            byte byteRet = 0;
            if (strAgvArriveLoc == "L0100" || strAgvArriveLoc == "L0200")
            {
                byteRet = 1;
            }
            else if (strAgvArriveLoc.Contains("charge_point") || strAgvArriveLoc.Contains("init"))
            {
                byteRet = 80;
            }
            else
            {
                byte bRow = byte.Parse(strAgvArriveLoc.Substring(1, 2));
                byte bColl = byte.Parse(strAgvArriveLoc.Substring(3, 2));
                byteRet = byte.Parse(bRow.ToString() + bColl.ToString());
            }

            //AddListBak("到位坐标!" + strAgvArriveLoc+"_"+byteRet.ToString());
            return byteRet;
        }
        public void ConnectWebsocket()
        {
            webSocket4NetClient = new WebSocket4Net.WebSocket(CTaskInfo.AGV_URL);
            webSocket4NetClient.Opened += WebSocket4Net_Opened;
            webSocket4NetClient.Error += Websocket_Error;
            webSocket4NetClient.Closed += new EventHandler(Websocket_Closed);
            webSocket4NetClient.MessageReceived += WebSocket4Net_MessageReceived;
            webSocket4NetClient.Open();
        }
        private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            string strReceive = e.Message;
            AddListBak_Agv(strReceive);
            try
            {
                if (strReceive.Contains("behavior_updated"))
                {
                    AGV.Model.TaskReport taskReport = new AGV.Model.TaskReport();
                    taskReport = Newtonsoft.Json.JsonConvert.DeserializeObject<AGV.Model.TaskReport>(strReceive);
                    cTaskStatus.Agv_Report_Task_Status = taskReport.msg.data;
                }
                else if (strReceive.Contains("percentage"))
                {
                    AGV.Model.BatteryReport batteryReport = new AGV.Model.BatteryReport();
                    batteryReport = Newtonsoft.Json.JsonConvert.DeserializeObject<AGV.Model.BatteryReport>(strReceive);
                    lbAgvBattery.Invoke(new EventHandler(delegate
                    {
                        cTaskStatus.AgvBattery = batteryReport.msg.percentage*100;
                        lbAgvBattery.Text = (cTaskStatus.AgvBattery).ToString("0") + " %";
                        if (batteryReport.msg.percentage * 100 > 35)
                        {
                            lbAgvBattery.BackColor = Color.Lime;
                        }
                        else
                        {
                            lbAgvBattery.BackColor = Color.Red;
                        }
                        if(cTaskStatus.AgvBattery<int.Parse(CTaskInfo.AgvAutoChangeLowValue))
                        {
                            //开启自动充电
                            if (CTaskInfo.CurrentTask == null)
                            {
                                string strAgvStatusTmp = "";
                                string strAgvTaskNoTmp = "";
                                lbTaskStatus.Invoke(new EventHandler(delegate {
                                    strAgvStatusTmp = lbTaskStatus.Text;
                                }));
                                lbTaskNo.Invoke(new EventHandler(delegate {
                                    strAgvTaskNoTmp = lbTaskNo.Text;
                                })); 
                                if (strAgvStatusTmp == "空闲"&& string.IsNullOrEmpty(strAgvTaskNoTmp))
                                {
                                    CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
                                    if (CTaskInfo.AgvCurrentLoc == CTaskInfo.AgvGetSetPointLoc)
                                    {
                                        cTaskStatus.AgvAutoChange = 1;
                                        AddListBak("开始自动充电");
                                    }
                                    else
                                    {
                                        AddListBak("自动充电时不在取货口位置,当前位置"+ CTaskInfo.AgvCurrentLoc+",取货口位置"+CTaskInfo.AgvGetSetPointLoc);
                                    }
                                }
                                else
                                {
                                    AddListBak("自动充电时AGV非空闲");
                                }
                            }
                            else
                            {
                                AddListBak("自动充电时有任务");
                            }
                        }
                    }));
                }
                else if (strReceive.Contains("diagnostics_agg"))
                {
                    AGV.Model.AlarmReport alarmReport = new AGV.Model.AlarmReport();
                    alarmReport = Newtonsoft.Json.JsonConvert.DeserializeObject<AGV.Model.AlarmReport>(strReceive);
                    foreach (AGV.Model.AlarmStatusItem aStatus in alarmReport.msg.status)
                    {
                        if (aStatus.name.Replace(" ", "") == "/STATUS/ESTOP")
                        {
                            if (aStatus.level == 1)
                            {
                                CTaskInfo.AgvIsHasAlarm = true;
                                CTaskInfo.AgvAlarmInfo = "AGV硬急停被触发"; 
                            }
                        }
                    }

                    if (CTaskInfo.AgvIsHasAlarm)
                    {
                        lbAGVAlarmInfo.Invoke(new EventHandler(delegate
                        {
                            lbAGVAlarmInfo.Text = CTaskInfo.AgvAlarmInfo;
                            lbAGVAlarmInfo.BackColor = Color.Red;
                        }));
                        lbAgvStatus.Invoke(new EventHandler(delegate
                        {
                            lbAgvStatus.BackColor = Color.Red;
                        }));
                    }
                    else
                    {
                        lbAGVAlarmInfo.Invoke(new EventHandler(delegate
                        {
                            lbAGVAlarmInfo.Text = "无";
                            lbAGVAlarmInfo.BackColor = Color.LightSteelBlue;
                        }));
                        lbAgvStatus.Invoke(new EventHandler(delegate
                        {
                            lbAgvStatus.BackColor = Color.LightSteelBlue;
                        }));
                    }


                }
            }
            catch(Exception exc)
            {
                AddListBak("AGV接收数据处理异常"+exc.Message);
            }
        }

        private void WebSocket4Net_Opened(object sender, EventArgs e)
        {
            AddListBak_Agv("AGV连接成功,可以准备发送数据");


            lbAgvLinkStatus.Invoke(new EventHandler(delegate {
                lbAgvLinkStatus.Text = "已连接";
                lbAgvLinkStatus.BackColor = Color.Lime;
            }));

            AGV.AgvMsgHelper agvMsgHelper = new AGV.AgvMsgHelper();
            string strSendMsg = agvMsgHelper.GetSendTaskReportInitCode();
            webSocket4NetClient.Send(strSendMsg);

            strSendMsg = agvMsgHelper.GetBatteryReportInitCode();
            webSocket4NetClient.Send(strSendMsg);

            //strSendMsg = agvMsgHelper.GetAlarmReportInitCode();
            //webSocket4NetClient.Send(strSendMsg);

        }

        private void Websocket_Error(object sender, EventArgs e)
        {
            SuperSocket.ClientEngine.ErrorEventArgs ev = (SuperSocket.ClientEngine.ErrorEventArgs)e;
            AddListBak_Agv("websocket错误" + ev.Exception);

            Thread.Sleep(1000);

            lbAgvLinkStatus.Invoke(new EventHandler(delegate {
                lbAgvLinkStatus.Text = "未连接";
                lbAgvLinkStatus.BackColor = Color.Red;
            }));

            FlushAgvShowInfo(false);
            if (webSocket4NetClient.State != WebSocket4Net.WebSocketState.Open && webSocket4NetClient.State != WebSocket4Net.WebSocketState.Connecting)
            {
                ConnectWebsocket();
            }
        }

        private void Websocket_Closed(object sender, EventArgs e)
        {
            AddListBak_Agv("websocket关闭");

            lbAgvLinkStatus.Invoke(new EventHandler(delegate {
                lbAgvLinkStatus.Text = "未连接";
                lbAgvLinkStatus.BackColor = Color.Red;
            }));

            Thread.Sleep(1000);
            if (webSocket4NetClient.State != WebSocket4Net.WebSocketState.Open && webSocket4NetClient.State != WebSocket4Net.WebSocketState.Connecting)
            {
                ConnectWebsocket();
            }
        }

        private void WebSocket4Net_SendMsg(string strMsg)
        {
            if (webSocket4NetClient.State == WebSocketState.Open)
            {
                AddListBak_Agv("websocket发送消息" + strMsg);
                webSocket4NetClient.Send(strMsg);
            }
            else
            {
                AddListBak("websocket发送消息时错误,websocket未连接!" + strMsg);
            }
        }

        private int UpdateTaskStatus(Int64 taskid, int status)
        {
            string strSql = "UPDATE W_TASK_AGV SET TASK_STATUS_CODE=" + status.ToString() + " WHERE TASK_ID=" + taskid.ToString();
            UYD_WCS.BLL.W_TASK_AGV bllTaskAgv = new UYD_WCS.BLL.W_TASK_AGV();
            return bllTaskAgv.ExecSql(strSql);
        }
        private int UpdateTaskStatus(string taskno, int status)
        {
            AddListBak("更新状态="+status.ToString());
            string strSql = "UPDATE W_TASK_AGV SET TASK_STATUS_CODE=" + status.ToString() + " WHERE TASK_NO=" + taskno.ToString();
            UYD_WCS.BLL.W_TASK_AGV bllTaskAgv = new UYD_WCS.BLL.W_TASK_AGV();
            return bllTaskAgv.ExecSql(strSql);
        }

        private void FlushAgvShowInfo(bool bIsShow)
        {
            if(!bIsShow)
            {
                lbAgvStatus.Invoke(new EventHandler(delegate {
                    lbAgvStatus.Text = "无";
                    lbAgvStatus.BackColor = Color.LightSteelBlue;
                }));
                lbAgvBattery.Invoke(new EventHandler(delegate {
                    lbAgvBattery.Text = "无";
                    lbAgvBattery.BackColor = Color.LightSteelBlue;
                }));
                lbAgvDestLoc.Invoke(new EventHandler(delegate {
                    lbAgvDestLoc.Text = "无";
                    lbAgvDestLoc.BackColor = Color.LightSteelBlue;
                }));
                lbAGVAlarmInfo.Invoke(new EventHandler(delegate {
                    lbAGVAlarmInfo.Text = "无";
                    lbAGVAlarmInfo.BackColor = Color.LightSteelBlue;
                }));
            }
        }
        #endregion


        #region 货叉信息交互
        ushort usTaskID = 100;
        /// <summary>
        /// 货叉任务下发
        /// </summary>
        /// <param name="setRow">目标排</param>
        /// <param name="setColl">目标列</param>
        /// <param name="setFloor">目标层</param>
        /// <param name="taskType">任务类型 1:移动任务 2:取货任务 3:放货任务</param>
        private void AGVForkSendCode(short setRow, short setColl, short setFloor, short taskType)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_SetRow_ToPlc_Addr, 1, setRow, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_SetColl_ToPlc_Addr, 1, setColl, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_SetFloor_ToPlc_Addr, 1, setFloor, 1, 1);
            if (usTaskID > 30000)
                usTaskID = 100;
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, usTaskID, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskType_ToPlc_Addr, 1, taskType, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskType_ToPlc_Addr, 1, taskType, 1, 1);
            Thread.Sleep(100);
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskStartFlag_ToPlc_Addr, 1, 1, 1, 1);
            usTaskID++;
            
            AddListBak("给货叉Plc下发新任务,任务号:"+usTaskID.ToString()+"任务类型(1=移动,2=取货,3=放货):"+taskType.ToString()+"排="+setRow.ToString()+",列="+setColl.ToString()+",层="+setFloor.ToString());

        }
        #endregion

        private void btnConnect_Click(object sender, EventArgs e)
        {

            if (webSocket4NetClient.State != WebSocket4Net.WebSocketState.Open && webSocket4NetClient.State != WebSocket4Net.WebSocketState.Connecting)
            {
                ConnectWebsocket();
            }
            else
            {
                AddListBak_Agv("AGV已经成功连接");
            }
        }

        private void btnDisCon_Click(object sender, EventArgs e)
        {
            webSocket4NetClient.Close();
        }

        private void btnSendTask_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbToLoc.Text.Trim()))
            {
                List<string> agvLocListTmp = new List<string>();
                agvLocListTmp.Add(tbToLoc.Text.Trim());
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode(agvLocListTmp));
            }
            else
            {
                AddListBak_Agv("请输入指令到达位置");
            }
        }

        private void btnSendTaskReportInit_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskReportInitCode());
        }

        private void btnSendPositionReportInit_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetPositionReportInitCode());
        }

        private void btnSendBatteryReportInit_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetBatteryReportInitCode());
        }

        private void btnSendAlarmReportInit_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetAlarmReportInitCode());
        }

        private void btnTaskCancle_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetTaskCancleCode());
        }

        private void btnTaskPause_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetTaskPauseRestoreCode(true));
        }

        private void btnTaskRestore_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetTaskPauseRestoreCode(false));
        }
        private void btnGetFinishToWcs_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x04);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void btnSetFinishToWcs_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x07);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void btnTaskFinishToWcs_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x08);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(tabControl2.SelectedIndex==1)
            {
                bool blSearch = false;
                DataSet ds = bllTaskAgv.GetList("");
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if(ds.Tables[0].Rows.Count>0)
                        {
                            blSearch = true;
                        }
                if (blSearch)
                    dgvTaskInfoSearch.DataSource = ds.Tables[0];
                else dgvTaskInfoSearch.DataSource = null;
                dgvTaskInfoSearch.AutoGenerateColumns = false;
            }
        }

        private void btnTaskStatus_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 0;
        }

        private void btnAgvControl_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 1;
        }

        private void btnForkControl_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 2;
        }

        private void btnLog_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 0;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmMain_XA_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("您真的要退出本系统吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                allThreadValue = 1;
                webSocket4NetClient.Close();
                Thread.Sleep(2000);
                System.Diagnostics.Process tt = System.Diagnostics.Process.GetProcessById(System.Diagnostics.Process.GetCurrentProcess().Id);
                tt.Kill();
            }
        }

        private int SendAutoChargeFlag = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            lbCurrentDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            lbCurrentTime.Text = DateTime.Now.ToString("HH:mm:ss");

            if (DateTime.Now.Hour == 5)
                SendAutoChargeFlag = 0;
            if(DateTime.Now.Hour==6)
            {
                if (SendAutoChargeFlag == 0)
                {
                    //开启自动充电
                    if (CTaskInfo.CurrentTask == null)
                    {
                        string strAgvStatusTmp = "";
                        string strAgvTaskNoTmp = "";
                        lbTaskStatus.Invoke(new EventHandler(delegate
                        {
                            strAgvStatusTmp = lbTaskStatus.Text;
                        }));
                        lbTaskNo.Invoke(new EventHandler(delegate
                        {
                            strAgvTaskNoTmp = lbTaskNo.Text;
                        }));
                        if (strAgvStatusTmp == "空闲" && string.IsNullOrEmpty(strAgvTaskNoTmp))
                        {
                            CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
                            if (CTaskInfo.AgvCurrentLoc == CTaskInfo.AgvGetSetPointLoc)
                            {
                                cTaskStatus.AgvAutoChange = 1;
                                AddListBak("开始自动充电");

                                SendAutoChargeFlag = 1;
                            }
                            else
                            {
                                AddListBak("自动充电时不在取货口位置,当前位置" + CTaskInfo.AgvCurrentLoc + ",取货口位置" + CTaskInfo.AgvGetSetPointLoc);
                            }
                        }
                        else
                        {
                            AddListBak("自动充电时AGV非空闲");
                        }
                    }
                    else
                    {
                        AddListBak("自动充电时有任务");
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x00);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x01);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x02);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x03);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button4_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x05);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button5_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x06);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void btnTaskStatus_MouseEnter(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatStyle = FlatStyle.Flat;
        }

        private void btnTaskStatus_MouseLeave(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatStyle = FlatStyle.Popup;
        }

        private void btnSendAlarmReportInit_MouseEnter(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatAppearance.BorderColor = Color.Yellow;
        }

        private void btnSendAlarmReportInit_MouseLeave(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatAppearance.BorderColor = Color.FromArgb(0, 0, 192); ;
        }

        private void lbTaskNo_MouseClick(object sender, MouseEventArgs e)
        {
            if (lbTaskNo.Text == "") return;
            contextMenuStrip2.Show(MousePosition.X, MousePosition.Y + 12);
        }

        private void tsmiTaskFinish_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务"+lbTaskNo.Text+"设置为任务完成状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 8);
            CTaskInfo.IsHasTask = false;
        }

        private void tsmiTaskDelete_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要删除任务" + lbTaskNo.Text + "?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            bllTaskAgv.Delete(CTaskInfo.CurrentTask.TASK_ID);
            CTaskInfo.IsHasTask = false;
        }

        private void btnSendToFork_Click(object sender, EventArgs e)
        {
            string strLoc = tbHandSendLocNo.Text.Trim();
            if(strLoc.Length<6)
            {
                MessageBox.Show("储位不正确!");
                return;
            }
            if (radioButtonMove.Checked)
            {
                short shRow = short.Parse(strLoc.Substring(0, 2));
                short shCell = short.Parse(strLoc.Substring(2, 2));
                short shFloor = short.Parse(strLoc.Substring(4, 2));
                AGVForkSendCode(shRow, shCell, shFloor, 1);

                AddListBak("手动下发货叉移动任务,货位:"+strLoc);
                lbForkTip.Text = "手动下发货叉移动任务,货位:" + strLoc;

            }
            else if (radioButtonGet.Checked)
            {
                short shRow = short.Parse(strLoc.Substring(0, 2));
                short shCell = short.Parse(strLoc.Substring(2, 2));
                short shFloor = short.Parse(strLoc.Substring(4, 2));
                AGVForkSendCode(shRow, shCell, shFloor, 2);
                AddListBak("手动下发货叉取货任务,货位:" + strLoc);
                lbForkTip.Text = "手动下发货叉取货任务,货位:" + strLoc;
            }
            else if (radioButtonSet.Checked)
            {
                short shRow = short.Parse(strLoc.Substring(0, 2));
                short shCell = short.Parse(strLoc.Substring(2, 2));
                short shFloor = short.Parse(strLoc.Substring(4, 2));
                AGVForkSendCode(shRow, shCell, shFloor, 3);
                AddListBak("手动下发货叉放货任务,货位:" + strLoc);
                lbForkTip.Text = "手动下发货叉放货任务,货位:" + strLoc;
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
        }

        private void btnReset_MouseDown(object sender, MouseEventArgs e)
        {

            AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1); 
            AddListBak("手动下发货叉复位=1");
            lbForkTip.Text = "手动下发货叉复位=1";
        }

        private void btnReset_MouseUp(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);
            AddListBak("手动下发货叉复位=0");
            lbForkTip.Text = "手动下发货叉复位=0";
        }

        private void btnTaskClear_Click(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);
            AddListBak("手动下发货叉任务清除");
            lbForkTip.Text = "手动下发货叉任务清除";
        }

        private void btnTaskContinue_Click(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_Task_Continue_ToPlc_Addr, 1, 1, 1, 1);
            AddListBak("手动下发货叉任务继续");
            lbForkTip.Text = "手动下发货叉任务继续";
        }

        private void btnEmergencyStop_Click(object sender, EventArgs e)
        {
            if (btnEmergencyStop.Text == "急停按下")
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_EmergencyStop_ToPlc_Addr, 1, 1, 1, 1);
                AddListBak("手动下发货叉急停按下");
                btnEmergencyStop.Text = "急停旋开";
                lbForkTip.Text = "手动下发货叉急停按下";
            }
            else
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_EmergencyStop_ToPlc_Addr, 1, 0, 1, 1);
                AddListBak("手动下发货叉急停旋开");
                btnEmergencyStop.Text = "急停按下";
                lbForkTip.Text = "手动下发货叉急停旋开";
            }
        }

        private void btnSendRemoteAuto_Click(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_RemoteAuto_ToPlc_Addr, 1, 1, 1, 1);
            AddListBak("手动下发货叉远程自动模式");
            lbForkTip.Text="手动下发货叉远程自动模式";
        }

        private void btnTaskLog_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 1;
        }

        private void btnAgvRunLog_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 2;
        }

        private void btnForkRunLog_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 3;
        }

        private void 待下发ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 待下发 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 0);
            CTaskInfo.IsHasTask = false;
            FlushPage();
            CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = false;

            CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = false;
            CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv = false;
        }

        private void 待执行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 待执行 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 1);
            CTaskInfo.IsHasTask = false;
            FlushPage();
            CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = false;

            CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = false;
            CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv = false;
        }

        private void 取货行走中ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 取货行走中 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 2);
            CTaskInfo.IsHasTask = false;
            FlushPage();
        }

        private void 到达取货位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 到达取货位 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 3);
            CTaskInfo.IsHasTask = false;
            FlushPage();
        }

        private void 取货完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 取货完成 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 4);
            CTaskInfo.IsHasTask = false;
            FlushPage();
        }

        private void 放货行走中ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 放货行走中 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 5);
            CTaskInfo.IsHasTask = false;
            FlushPage();
        }

        private void 到达放货位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 到达放货位 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 6);
            CTaskInfo.IsHasTask = false;
            FlushPage();
        }

        private void 放货完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 放货完成 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 7);
            CTaskInfo.IsHasTask = false;
            FlushPage();
        }

        private void 任务完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 任务完成 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(CTaskInfo.CurrentTask.TASK_ID, 8);
            CTaskInfo.IsHasTask = false;
            FlushPage();
            CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = false;

            CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = false;
            CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv = false;
        }

        private void 任务删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要删除任务" + lbTaskNo.Text + "?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            bllTaskAgv.Delete(CTaskInfo.CurrentTask.TASK_ID);
            CTaskInfo.IsHasTask = false;
            FlushPage();

            CTaskInfo.CheckForkStatus_Before_Move_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Get_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Move_Set_SendedToPlc = false;
            CTaskInfo.CheckForkStatus_Before_Set_SendedToPlc = false;

            CTaskInfo.CheckForkStatus_Get_Finished_SendedToAgv = false;
            CTaskInfo.CheckForkStatus_Set_Finished_SendedToAgv = false;
        }

        private void btnReadPlc_Click(object sender, EventArgs e)
        {
            if (checkBoxReadBool.Checked)
            {
                PLCMsgModel plcMM= plcSRM1.PLCReadBool(tbReadPlcAddr.Text.Trim());
                if (plcMM.Code == 1)
                {
                    bool bRead = (bool)plcMM.Val;
                    tbReadResult.Text = bRead ? "true" : "false";
                }
                else
                {
                    tbReadResult.Text = plcMM.Msg;
                }
            }
            else
            {
                PLCMsgModel plcMM = plcSRM1.PLCReadByte(tbReadPlcAddr.Text.Trim());
                if (plcMM.Code == 1)
                {
                    short bRead = (short)plcMM.Val;
                    tbReadResult.Text = bRead.ToString();
                }
                else
                {
                    tbReadResult.Text = plcMM.Msg;
                }
            }
        }

        private void btnWritePlc_Click(object sender, EventArgs e)
        {
            if (checkBoxWriteBool.Checked)
            {
                PLCMsgModel plcMM = plcSRM1.PLCWrite(tbWritePLcAddr.Text.Trim(),bool.Parse(tbWritePLcValue.Text.Trim()));
                if (plcMM.Code == 1)
                {
                    tbWritePLcValue.Text = "写入成功";
                }
                else
                {
                    tbWritePLcValue.Text = plcMM.Msg;
                }
                tbWritePLcValue.Focus();
                tbWritePLcValue.Select();
                tbWritePLcValue.SelectAll();
            }
            else
            {
                PLCMsgModel plcMM = plcSRM1.PLCWrite(tbWritePLcAddr.Text.Trim(), short.Parse(tbWritePLcValue.Text.Trim()));
                if (plcMM.Code == 1)
                {
                    tbWritePLcValue.Text = "写入成功";
                }
                else
                {
                    tbWritePLcValue.Text = plcMM.Msg;
                }
                tbWritePLcValue.Focus();
                tbWritePLcValue.Select();
                tbWritePLcValue.SelectAll();
            }


        }

        private void btnSendChargingTask_Click(object sender, EventArgs e)
        {

            List<string> agvLocListTmp = new List<string>();
            agvLocListTmp.Add("charge_point");
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode(agvLocListTmp));
        }

        private void btnSendToInitLocTask_Click(object sender, EventArgs e)
        {
            List<string> agvLocListTmp = new List<string>();
            agvLocListTmp.Add("initial_pose");
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode(agvLocListTmp));
        }

        private void btnSendCode_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(tbSendCode.Text.Trim());
        }

        private void btnTurnleft90_Click(object sender, EventArgs e)
        {
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublish_RotateCode("turn_left"));
        }

        private void btnTurnRight90_Click(object sender, EventArgs e)
        {
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublish_RotateCode("turn_right"));
        }

        private void btnTurnBack_Click(object sender, EventArgs e)
        {

            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublish_RotateCode("turn_back"));
        }

        private void btnSendInTask_Click(object sender, EventArgs e)
        {
            if (tbToLoc.Text == "") return;
            if (tbToLoc.Text.Length<5) return;
            if (CTaskInfo.WareName == "XA")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                listInputKey.Add("three_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add("L0000R");
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00R");
                listInputValue.Add(tbToLoc.Text.Trim());
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
            }
            else if (CTaskInfo.WareName == "XJ")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                listInputKey.Add("three_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add("L0000R");
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00R");
                listInputValue.Add(tbToLoc.Text.Trim());
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
            }
            else if (CTaskInfo.WareName == "HY")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                listInputKey.Add("three_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add("L0000R");
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00R");
                listInputValue.Add(tbToLoc.Text.Trim());
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务
            }
            else if (CTaskInfo.WareName == "ZN")
            {

                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00R");
                listInputValue.Add(tbToLoc.Text.Trim());
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务

            }
            else if (CTaskInfo.WareName == "HGZ")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00R");
                listInputValue.Add(tbToLoc.Text.Trim());
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("instock_task", listInputKey, listInputValue));//需要修改一下AGV里面的任务

            }

        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            if (tbToLoc.Text == "") return;
            if (tbToLoc.Text.Length < 5) return;
            List<string> listInputKey = new List<string>();
            listInputKey.Add("from_site");
            listInputKey.Add("des_site");
            List<string> listInputValue = new List<string>();
            string strToLoc = tbToLoc.Text.Trim();
            if (strToLoc == CTaskInfo.AgvGetSetPointLoc)
            {
                listInputValue.Add("L0000R");
                listInputValue.Add("");
            }
            else
            {
                listInputValue.Add(strToLoc.Substring(0,3)+"00C");
                listInputValue.Add("");
            }
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("back_task", listInputKey, listInputValue));
        }

        private void btnSendOutTask_Click(object sender, EventArgs e)
        {
            if (tbToLoc.Text == "") return;
            if (tbToLoc.Text.Length < 5) return;
            if (CTaskInfo.WareName == "XA")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                listInputKey.Add("three_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00C");
                listInputValue.Add("L0000C");//
                listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);//这两个参数可以固定下来
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
            }
            else if (CTaskInfo.WareName == "XJ")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                listInputKey.Add("three_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00C");
                listInputValue.Add("L0000C");//
                listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);//这两个参数可以固定下来
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
            }
            else if (CTaskInfo.WareName == "HY")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                listInputKey.Add("three_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00C");
                listInputValue.Add("L0000C");//
                listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);//这两个参数可以固定下来
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
            }
            else if (CTaskInfo.WareName == "ZN")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00C");
                listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));

            }
            else if (CTaskInfo.WareName == "HGZ")
            {
                List<string> listInputKey = new List<string>();
                listInputKey.Add("from_site");
                listInputKey.Add("des_site");
                List<string> listInputValue = new List<string>();
                listInputValue.Add(tbToLoc.Text.Trim().Substring(0, 3) + "00C");
                listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);//这两个参数可以固定下来
                WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("outstock_task", listInputKey, listInputValue));
            }
        }

        private void btnToZeroPoint_Click(object sender, EventArgs e)
        {
            List<string> listInputKey = new List<string>();
            listInputKey.Add("from_site");
            listInputKey.Add("des_site");
            List<string> listInputValue = new List<string>();
            listInputValue.Add(CTaskInfo.AgvGetSetPointLoc);
            listInputValue.Add("");
            ////WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("initial_task", listInputKey, listInputValue));
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("chargepointtogetsetpoint_task", listInputKey, listInputValue));
        }

        #region 储位坐标

        private void btnAddAllLoc_Click(object sender, EventArgs e)
        {

            try
            {

                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                string strSql = "DELETE FROM w_pos ";
                bllPos.ExeSql(strSql);


                for (int i=0;i< numericUpDownRow.Value;i++)
                {
                    for (int j = 0; j < numericUpDownColl.Value; j++)
                    {
                        if (i == 0 && j == 0)
                        {
                            UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                            modelPos.LOC_NO = "L0000R";
                            modelPos.LOC_NO_TYPE = "入库点";
                            modelPos.X = decimal.Parse(tbPosX.Text.Trim());
                            modelPos.Y = decimal.Parse(tbPosY.Text.Trim());
                            modelPos.Z = decimal.Parse(tbPosZ.Text.Trim());
                            modelPos.W = decimal.Parse(tbPosW.Text.Trim());

                            bllPos.Add(modelPos);

                            modelPos = new UYD_WCS.Model.W_POS();
                            modelPos.LOC_NO = "L0000C";
                            modelPos.LOC_NO_TYPE = "出库点";
                            modelPos.X = decimal.Parse(tbPosX.Text.Trim());
                            modelPos.Y = decimal.Parse(tbPosY.Text.Trim());
                            modelPos.Z = decimal.Parse(tbPosZ.Text.Trim());
                            modelPos.W = decimal.Parse(tbPosW.Text.Trim());

                            bllPos = new UYD_WCS.BLL.W_POS();
                            bllPos.Add(modelPos);
                        }
                        else if(i>0 && j==0)
                        {
                            UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                            modelPos.LOC_NO = "L"+i.ToString("00")+"00R";
                            modelPos.LOC_NO_TYPE = "入库点";
                            modelPos.X = decimal.Parse(tbPosX.Text.Trim());
                            modelPos.Y = decimal.Parse(tbPosY.Text.Trim());
                            modelPos.Z = decimal.Parse(tbPosZ.Text.Trim());
                            modelPos.W = decimal.Parse(tbPosW.Text.Trim());

                            bllPos.Add(modelPos);

                            modelPos = new UYD_WCS.Model.W_POS();
                            modelPos.LOC_NO = "L"+ i.ToString("00") + "00C";
                            modelPos.LOC_NO_TYPE = "出库点";
                            modelPos.X = decimal.Parse(tbPosX.Text.Trim());
                            modelPos.Y = decimal.Parse(tbPosY.Text.Trim());
                            modelPos.Z = decimal.Parse(tbPosZ.Text.Trim());
                            modelPos.W = decimal.Parse(tbPosW.Text.Trim());

                            bllPos.Add(modelPos);
                        }
                        else if (i > 0 && j > 0)
                        {
                            UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                            modelPos.LOC_NO = "L" + i.ToString("00") + j.ToString("00");
                            modelPos.LOC_NO_TYPE = "储位";
                            modelPos.X = decimal.Parse(tbPosX.Text.Trim());
                            modelPos.Y = decimal.Parse(tbPosY.Text.Trim());
                            modelPos.Z = decimal.Parse(tbPosZ.Text.Trim());
                            modelPos.W = decimal.Parse(tbPosW.Text.Trim());

                            bllPos.Add(modelPos);
                        }
                    }
                }

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void SearchPos()
        {
            dgvPos.DataSource = null;
            UYD_WCS.BLL.W_POS modelPos = new UYD_WCS.BLL.W_POS();
            DataSet ds= modelPos.GetAllList();
            dgvPos.AutoGenerateColumns = false;
            dgvPos.DataSource = ds.Tables[0];
        }

        private void btnAddOneLoc_Click(object sender, EventArgs e)
        {
            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text == "储位")
                    modelPos.LOC_NO = "L" + numericUpDownRow.Value.ToString("00") + numericUpDownColl.Value.ToString("00");
                else if (comboBoxLocType.Text == "入库点")
                    modelPos.LOC_NO = "L" + numericUpDownRow.Value.ToString("00") + numericUpDownColl.Value.ToString("00")+"R";
                else if (comboBoxLocType.Text == "出库点")
                    modelPos.LOC_NO = "L" + numericUpDownRow.Value.ToString("00") + numericUpDownColl.Value.ToString("00")+"C";
                modelPos.LOC_NO_TYPE = comboBoxLocType.Text;
                modelPos.X = decimal.Parse(tbPosX.Text.Trim());
                modelPos.Y = decimal.Parse(tbPosY.Text.Trim());
                modelPos.Z = decimal.Parse(tbPosZ.Text.Trim());
                modelPos.W = decimal.Parse(tbPosW.Text.Trim());

                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();

                string strSql = "DELETE FROM w_pos where loc_no='"+modelPos.LOC_NO+"' ";
                bllPos.ExeSql(strSql);

                bllPos.Add(modelPos);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnDelOneLoc_Click(object sender, EventArgs e)
        {

            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text == "储位")
                    modelPos.LOC_NO = "L" + numericUpDownRow.Value.ToString("00") + numericUpDownColl.Value.ToString("00");
                else if (comboBoxLocType.Text == "入库点")
                    modelPos.LOC_NO = "L" + numericUpDownRow.Value.ToString("00") + numericUpDownColl.Value.ToString("00") + "R";
                else if (comboBoxLocType.Text == "出库点")
                    modelPos.LOC_NO = "L" + numericUpDownRow.Value.ToString("00") + numericUpDownColl.Value.ToString("00") + "C";

                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.Delete(modelPos.LOC_NO);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowX_Click(object sender, EventArgs e)
        {
            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return; 
                }
                string strSql = " update w_pos set x=" + tbPosX.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowY_Click(object sender, EventArgs e)
        {

            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return;
                }
                string strSql = " update w_pos set Y=" + tbPosY.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowZ_Click(object sender, EventArgs e)
        {

            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return;
                }
                string strSql = " update w_pos set Z=" + tbPosZ.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowW_Click(object sender, EventArgs e)
        {
            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return;
                }
                string strSql = " update w_pos set W=" + tbPosW.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollX_Click(object sender, EventArgs e)
        {

            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return;
                }
                string strSql = " update w_pos set X=" + tbPosX.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%"+numericUpDownColl.Value.ToString("00") + "'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollY_Click(object sender, EventArgs e)
        {
            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return;
                }
                string strSql = " update w_pos set Y=" + tbPosY.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%" + numericUpDownColl.Value.ToString("00") + "'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollZ_Click(object sender, EventArgs e)
        {

            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return;
                }
                string strSql = " update w_pos set Z=" + tbPosZ.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%" + numericUpDownColl.Value.ToString("00") + "'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollW_Click(object sender, EventArgs e)
        {

            try
            {
                UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                if (comboBoxLocType.Text != "储位")
                {
                    MessageBox.Show("提示", "只能更新储位坐标");
                    return;
                }
                string strSql = " update w_pos set W=" + tbPosW.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%" + numericUpDownColl.Value.ToString("00") + "'";
                UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                bllPos.ExeSql(strSql);

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnLocPosSet_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 4;
            SearchPos();
        }

        #endregion

        private void btnTaskIDSetZero_Click(object sender, EventArgs e)
        {

            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
            AddListBak("手动下发货叉作业号清0");
            lbForkTip.Text = "手动下发货叉作业号清0";
        }

        private void button14_Click(object sender, EventArgs e)
        {
            if (tbToLoc.Text == "") return;
            if (tbToLoc.Text.Length < 5) return;
            List<string> listInputKey = new List<string>();
            listInputKey.Add("from_site");
            listInputKey.Add("des_site");
            List<string> listInputValue = new List<string>();
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("tozeropoint_task", listInputKey, listInputValue));

        }

        private void btnToFrom_Click(object sender, EventArgs e)
        {

            if (tbToLoc.Text == "") return;
            if (tbToLoc.Text.Length < 5) return;
            List<string> listInputKey = new List<string>();
            listInputKey.Add("from_site");
            listInputKey.Add("des_site");
            List<string> listInputValue = new List<string>();
            string strToLoc = tbToLoc.Text.Trim();
                listInputValue.Add(tbToLoc.Text.Trim());
                listInputValue.Add("");
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("back_task", listInputKey, listInputValue));

        }

        private void button12_Click(object sender, EventArgs e)
        {

            if (tbToLoc.Text == "") return;
            if (tbToLoc.Text.Length < 5) return;
            List<string> listInputKey = new List<string>();
            listInputKey.Add("from_site");
            listInputKey.Add("des_site");
            List<string> listInputValue = new List<string>();
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("tochargepoint_task", listInputKey, listInputValue));

        }

        private void btnZeroCharge_Click(object sender, EventArgs e)
        {
            if (tbToLoc.Text == "") return;
            if (tbToLoc.Text.Length < 5) return;
            List<string> listInputKey = new List<string>();
            listInputKey.Add("from_site");
            listInputKey.Add("des_site");
            List<string> listInputValue = new List<string>();
            WebSocket4Net_SendMsg(agvMsgHelper.GetSendTaskPublishCode("autocharge_on", listInputKey, listInputValue));

        }

        private void lbForkGetFinished_Click(object sender, EventArgs e)
        {
            bool blUpGetFinishStatus = false;
            if(lbForkGetFinished.BackColor == Color.Lime)
            {
                blUpGetFinishStatus = false;
            }
            else
            {
                blUpGetFinishStatus = true;
            }
            plcSRM1.PLCWrite("DB540.24.1", blUpGetFinishStatus);

        }

        private void lbForkSetFinished_Click(object sender, EventArgs e)
        {
            bool blUpSetFinishStatus = false;
            if (lbForkSetFinished.BackColor == Color.Lime)
            {
                blUpSetFinishStatus = false;
            }
            else
            {
                blUpSetFinishStatus = true;
            }
            plcSRM1.PLCWrite("DB540.24.2", blUpSetFinishStatus);
        }

        private void lbForkTaskFinished_Click(object sender, EventArgs e)
        {
            bool blUpSetFinishStatus = false;
            if (lbForkTaskFinished.BackColor == Color.Lime)
            {
                blUpSetFinishStatus = false;
            }
            else
            {
                blUpSetFinishStatus = true;
            }
            plcSRM1.PLCWrite("DB540.24.5", blUpSetFinishStatus);
        }
    }
}
